package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.ExcelFormatUtil;
import cn.stylefeng.guns.sys.core.util.LogUtil;
import cn.stylefeng.guns.sys.core.util.PageUtil;
import cn.stylefeng.guns.sys.modular.rest.service.NameRelationService;
import cn.stylefeng.guns.sys.modular.system.controller.BaseFrontController;
import cn.stylefeng.guns.sys.modular.system.db4.mapper.BizShopMapper;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.*;
import cn.stylefeng.guns.sys.modular.system.model.ScmHuopeiDto;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyCwHuopeiParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyCwHpDto;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyCwHuopeiResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyCwHuopeiService;
import cn.stylefeng.guns.sys.modular.system.service.PushMsgService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.HttpContext;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static cn.afterturn.easypoi.util.PoiCellUtil.getCellValue;

/**
 * <p>
 * 货赔表 服务实现类
 * </p>
 *
 * @author 
 * @since 2021-11-02
 */
@Service
public class BtyCwHuopeiServiceImpl extends ServiceImpl<BtyCwHuopeiMapper, BtyCwHuopei> implements BtyCwHuopeiService {
    private Logger logger = LoggerFactory.getLogger(BtyCwHuopeiServiceImpl.class);

    @Autowired
    private BtyCwPankuiMapper btyCwPankuiMapper;
    @Autowired
    private YybbMapper yybbMapper;
    @Autowired
    private BtyCwJsMapper cwJsMapper;
    @Autowired
    private BizShopMapper bizShopMapper;
    @Autowired
    private PushMsgService pushMsgService;
    @Autowired
    private NameRelationService nameRelationService;

    @Override
    public void add(BtyCwHuopeiParam param){
        BtyCwHuopei entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyCwHuopeiParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyCwHuopeiParam param){
        BtyCwHuopei oldEntity = getOldEntity(param);
        BtyCwHuopei newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyCwHuopeiResult findBySpec(BtyCwHuopeiParam param){
        return null;
    }

    @Override
    public List<BtyCwHuopeiResult> findListBySpec(BtyCwHuopeiParam param){
        return null;
    }

    /**
     * 货赔列表（拼接手动分页）
     * @param param
     * @param date
     * @return
     */
    @Override
    public LayuiPageInfo findPageBySpec(BtyCwHuopeiParam param, String date){

        HttpServletRequest request = HttpContext.getRequest();
        int limit = 20;
        int page = 1;
        //每页多少条数据
        String limitString = request.getParameter("limit");
        if (ToolUtil.isNotEmpty(limitString)) {
            limit = Integer.parseInt(limitString);
        }
        //第几页
        String pageString = request.getParameter("page");
        if (ToolUtil.isNotEmpty(pageString)) {
            page = Integer.parseInt(pageString);
        }

        //当前登陆者姓名
        String name = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        Page pageContext = getPageContext();
//        IPage page = null;
        List<String> list;
        List<BtyCwHuopeiResult> pageList = new ArrayList<>();

        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
            list = baseMapper.getJsPrice(param, date, null);//无酒水卖价的店
//            page = this.baseMapper.customPageList(pageContext, param, null);
            pageList = this.baseMapper.customPageList(param, date, null);
            for (BtyCwHuopeiResult result : pageList) {
                if (ToolUtil.isNotEmpty(list)){
                    if (list.contains(result.getShopCode())){
                        result.setPriceSta("无");
                    }else {
                        result.setPriceSta("有");
                    }

                }
            }
        }else if (roleNames.contains("会计")){
            //获取成本会计所对应店名
            List<String> dm = this.baseMapper.dmList(name);
            if (ToolUtil.isEmpty(dm)){
                return new LayuiPageInfo();
            }
            list = baseMapper.getJsPrice(param, date, dm);//无酒水卖价的店

//            page = this.baseMapper.customPageList(pageContext, param, dm);
            pageList = this.baseMapper.customPageList(param, date, dm);
            for (BtyCwHuopeiResult result : pageList) {
                if (ToolUtil.isNotEmpty(list)){
                    if (list.contains(result.getShopCode())){
                        result.setPriceSta("无");
                    }else {
                        result.setPriceSta("有");
                    }

                }
            }
        }

        IPage page1 = new Page();
        page1.setCurrent(page);
        page1.setRecords(PageUtil.listPage(page,limit,pageList));
        page1.setSize(limit);
        page1.setTotal(pageList.size());
        page1.setPages(getPages(page1.getSize(), page1.getTotal()));
        LayuiPageInfo pageBySpec = LayuiPageFactory.createPageInfo(page1);
        pageBySpec.setData(PageUtil.listPage(page,limit,pageList));
        return pageBySpec;
    }

    private long getPages(long size, long total) {
        if (size == 0L) {
            return 0L;
        } else {
            long pages = total / size;
            if (total % size != 0L) {
                ++pages;
            }

            return pages;
        }
    }

    /**
     * 货赔列表
     * @param param
     * @param date
     * @return
     */
    @Override
    public LayuiPageInfo hpList(BtyCwHuopeiParam param, String date, Long provinceId, Long cityId){

        //当前登陆者姓名
        String name = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        Page pageContext = getPageContext();
        IPage page = null;
        List<String> dm = new ArrayList<>();

        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){

            dm = this.baseMapper.getDm(cityId,null, provinceId);
            page = this.baseMapper.hpList(pageContext, param, date, dm);

        }else if (roleNames.contains("会计")){

            //获取成本会计所对应店名
            dm = this.baseMapper.getDm(cityId,name,provinceId);
            page = this.baseMapper.hpList(pageContext, param, date, dm);

        }
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(BtyCwHuopeiParam param){
        return param.getHuopeiId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyCwHuopei getOldEntity(BtyCwHuopeiParam param) {
        return this.getById(getKey(param));
    }

    private BtyCwHuopei getEntity(BtyCwHuopeiParam param) {
        BtyCwHuopei entity = new BtyCwHuopei();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    /**
     * 导入excel
     * @param fileName
     * @param file
     * @return
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Boolean batchImport(String fileName, MultipartFile file) throws Exception {

        boolean notNull = false;
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }

        boolean isExcel2003 = true;//Excel2003
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }

        //TODO-1 默认就一个sheet
        Sheet sheet = wb.getSheetAt(0);

        //获取业务日期
        Row row1 = sheet.getRow(0);
        String name = row1.getCell(0).getStringCellValue();
        String begin = name.split("业务日期:|至|\\)")[1];
        String end = name.split("业务日期:|至|\\)")[2];

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date beginTime = sdf.parse(begin);
        Date endTime = sdf.parse(end);

        //shopCode集合
        List<String> codeList = new ArrayList();

        List<BtyCwHuopei> huopeiList = new ArrayList();

        //循环行row
        int lastRowNum = sheet.getLastRowNum() - 1;
        for (int r = 2; r <= lastRowNum; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }

            //获取单元格
            Cell cell = row.getCell(0);
            if (ToolUtil.isNotEmpty(cell)) {
                cell.setCellType(CellType.STRING);
            }


            String number = row.getCell(0) == null ? "" : row.getCell(0).getStringCellValue();//序号
            String shopCode = row.getCell(1) == null ? "" : row.getCell(1).getStringCellValue();//门店编号
            String shopName = row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue();//门店名称
            String className = row.getCell(6) == null ? "" : row.getCell(6).getStringCellValue();//品项类别名称
            String proCode = row.getCell(7) == null ? "" : row.getCell(7).getStringCellValue();//品项编号
            String proName = row.getCell(8) == null ? "" : row.getCell(8).getStringCellValue();//品项名称
            String spec = row.getCell(9) == null ? "" : row.getCell(9).getStringCellValue();//规格
            String unit = row.getCell(10) == null ? "" : row.getCell(10).getStringCellValue();//单位
            //非税单价
            String price = getCellValue(row.getCell(11));
            //理论耗用数量
            String thNum = getCellValue(row.getCell(12));
            //实际耗用数量
            String realNum = getCellValue(row.getCell(13));
            //耗用数量分差
            String numTotal = getCellValue(row.getCell(14));
            //耗用金额分差
            String amountTotal = getCellValue(row.getCell(15));
            Long createUser = LoginContextHolder.getContext().getUserId();//创建者
            Date createTime = new Date();//创建时间

            //餐具（包含山西餐具） 及 山西酒水不统计
            if (ToolUtil.isNotEmpty(shopCode) && !className.contains("餐具") && !className.contains("山西")){

                BtyCwHuopei cwHuopei = new BtyCwHuopei();
//                cwHuopei.setNum(number);
                cwHuopei.setShopCode(shopCode);
                cwHuopei.setShopName(shopName);
                cwHuopei.setClassName(className);
                cwHuopei.setProCode(proCode);
                cwHuopei.setProName(proName);
                cwHuopei.setSpec(spec);
                cwHuopei.setUnit(unit);
                if (className.contains("酒水")){
                    cwHuopei.setPrice("0");//非税成本单价
                    cwHuopei.setAmountTotal("0");//耗用金额分差
                }else {
                    cwHuopei.setPrice(price);
                    cwHuopei.setAmountTotal(amountTotal);
                }
                cwHuopei.setThNum(thNum);
                cwHuopei.setRealNum(realNum);
                cwHuopei.setNumTotal(numTotal);
                cwHuopei.setCreateUser(createUser);
                cwHuopei.setCreateTime(createTime);
                cwHuopei.setBeginTime(beginTime);
                cwHuopei.setEndTime(endTime);
                cwHuopei.setScmStatus(1);//0-> 供应链获取；1->数据导入

                huopeiList.add(cwHuopei);
                codeList.add(shopCode);
            }

        }

        //每100条保存一次
        for(int i = 0; i < codeList.size();){
            int i2 = (i + 300);
            i2 = i2 > codeList.size() ? codeList.size() : i2;
            List<String> sub = codeList.subList(i, i2);
            //删除货赔表数据
            baseMapper.deleteList(sub, endTime);
            //删除盘亏表数据
            btyCwPankuiMapper.deleteList(sub, endTime);
            i = i2;
        }


//        for (String code : codeList) {
//            //查询数据库中是否存在该店该时间段的数据
//            int num = baseMapper.count(code, endTime);
//            if (num != 0){
//                //删除货赔表数据
//                baseMapper.delete(code, endTime);
//                //查询盘亏表是否存在该店该时间段的数据
//                int count = btyCwPankuiMapper.count(code, endTime);
//                if (count != 0){
//                    //删除盘亏表数据
//                    btyCwPankuiMapper.delete(code, endTime);
//                }
//
//            }
//        }

//        for (BtyCwHuopei huopei : huopeiList) {
//
//            //获取该店营业额
//            BigDecimal turnover = yybbMapper.getYye(huopei.getShopName(), begin.substring(0, 6));
//            huopei.setTurnover(turnover);
//
//            baseMapper.insert(huopei);
//        }

        if(ToolUtil.isNotEmpty(huopeiList)){
            //每100条保存一次
            for(int i = 0; i < huopeiList.size();){
                int i2 = (i + 80);
                i2 = i2 > huopeiList.size() ? huopeiList.size() : i2;
                List<BtyCwHuopei> sub = huopeiList.subList(i, i2);
                notNull = baseMapper.insertHp(sub);
                i = i2;
            }
        }

        return notNull;
    }

    /**
     * 货赔表详细（酒水与自采酒水分开显示）- app
     * @param param
     * @param date
     * @return
     */
    public List<BtyCwHuopei> getHuopeiApp(BtyCwHuopei param, String date) {
        //要导出的list
        List<BtyCwHuopei> list = new ArrayList<>();

        //获取该店的货赔信息
        List<BtyCwHuopei> huopeiList = baseMapper.getHuopei(param,date);
        //查询该店的品相类别
        List<BtyCwHuopei> className = baseMapper.selectClassName(param);
        //获取所有时间段
        List<BtyCwHuopei> timeList = baseMapper.selectTime(param, date);

        //遍历时间
        if (CollectionUtil.isNotEmpty(timeList)){
            for (BtyCwHuopei time : timeList) {
                int i = 0;

                BigDecimal turnover = BigDecimal.ZERO;
                BigDecimal five = BigDecimal.ZERO;
                BigDecimal ten = BigDecimal.ZERO;
                String fiveM = "";//免赔（营业额百分之五取整）

                Map<String, String> map = new HashMap();

                if (CollectionUtil.isNotEmpty(className)) {
                    //循环该店品相类别
                    for (BtyCwHuopei name : className) {
                        //循环的时间相同
//                        if (name.getBeginTime().equals(time.getBeginTime()) && name.getShopCode().equals(time.getShopCode())){
                        if (name.getEndTime().equals(time.getEndTime()) && name.getShopCode().equals(time.getShopCode())){

                            BigDecimal sum1 = new BigDecimal(0);//理论耗用数量
                            BigDecimal sum2 = new BigDecimal(0);//实际耗用数量
                            BigDecimal sum3 = new BigDecimal(0);//耗用数量分差
                            BigDecimal sum4 = new BigDecimal(0);//耗用金额分差
                            BigDecimal sum5 = new BigDecimal(0);//耗用金额分差(酒水，只取负数)

                            if (CollectionUtil.isNotEmpty(huopeiList)) {
                                //循环该店货赔信息
                                for (BtyCwHuopei huopei : huopeiList) {
                                    //品相类别相同
//                                    if (name.getClassName().equals(huopei.getClassName()) && time.getBeginTime().equals(huopei.getBeginTime())) {
                                    if (name.getClassName().equals(huopei.getClassName()) && time.getEndTime().equals(huopei.getEndTime())) {

                                        //修改序号
                                        huopei.setNum(String.valueOf(i++));
                                        baseMapper.updateNum(huopei.getNum(), huopei.getShopCode(), huopei.getProCode(), huopei.getEndTime());

                                        sum1 = sum1.add(huopei.getThNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getThNum()));
                                        sum2 = sum2.add(huopei.getRealNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getRealNum()));
                                        sum3 = sum3.add(huopei.getNumTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getNumTotal()));
                                        sum4 = sum4.add(huopei.getAmountTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));

                                        //酒水耗用金额分差小计 只取负数的合计
                                        if(name.getClassName().contains("酒水") && ToolUtil.isNotEmpty(huopei.getAmountTotal())){
                                            sum5 = sum5.add(new BigDecimal(huopei.getAmountTotal()).compareTo(BigDecimal.ZERO) >= 0 ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
                                        }

//                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                                        String dateSdf = "";
//
//                                        if(ToolUtil.isNotEmpty(param.getBeginTime())){
//                                            dateSdf = sdf.format(param.getBeginTime()).substring(0, 7);
//                                        }else if (ToolUtil.isNotEmpty(date)){
//                                            dateSdf = date;
//                                        }

                                        //获取营业额
//                                        turnover = yybbMapper.getYye(huopei.getShopName(), dateSdf);
                                        turnover = yybbMapper.getYye(huopei.getShopName(), huopei.getBeginTime(), huopei.getEndTime());

                                        if (turnover == null){
                                            turnover = BigDecimal.ZERO;
                                        }
                                        turnover.setScale(2, BigDecimal.ROUND_HALF_UP);//截取两位
                                        huopei.setTurnover(turnover);

                                        five = turnover.multiply(new BigDecimal(0.0005)).setScale(2, BigDecimal.ROUND_HALF_UP);//营业额万分之五
                                        ten = turnover.multiply(new BigDecimal(0.001)).setScale(2, BigDecimal.ROUND_HALF_UP);//营业额万分之十
                                        huopei.setFive(five);
                                        huopei.setTen(ten);

                                        list.add(huopei);

                                    }
                                }
                            }

                            name.setNum("小计");
                            name.setThNum(String.valueOf(sum1));//理论耗用数量
                            name.setRealNum(String.valueOf(sum2));//实际耗用数量
                            name.setNumTotal(String.valueOf(sum3));//耗用数量分差
                            if (name.getClassName().equals("酒水")){
                                name.setAmountTotal(String.valueOf(sum5));//耗用金额分差
                            }else {
                                name.setAmountTotal(String.valueOf(sum4));//耗用金额分差
                            }
                            list.add(name);

                            //修改数据库各小计
                            BtyCwHuopei huopei = new BtyCwHuopei();

                            fiveM = String.valueOf(Math.round(five.doubleValue()));//免赔（营业额百分之五取整）

                            if (name.getClassName().equals("冻货")) {
                                huopei.setDhThSum(String.valueOf(sum1));//冻货理论耗用数量小计
                                huopei.setDhRealSum(String.valueOf(sum2));//冻货实际耗用数量小计
                                huopei.setDhAmSum(String.valueOf(sum4));//冻货耗用金额分差小计
                                huopei.setDhNumSum(String.valueOf(sum3));//冻货耗用数量分差小计

                                //清江鱼盘亏
                                long qjyPk = Math.round(Double.valueOf(huopei.getDhAmSum()));
                                qjyPk = qjyPk >= 0 ? 0 : qjyPk;
                                //四舍五入取整
//                                map.put("qjyPk", String.valueOf(Math.round(Double.valueOf(huopei.getDhAmSum()))));
                                map.put("qjyPk", String.valueOf(qjyPk));

                                BigDecimal dhAmSum = new BigDecimal(huopei.getDhAmSum());
                                //理论货赔 -> 盘亏+免赔+其他免赔
                                BigDecimal qjyLlhp = new BigDecimal(map.get("qjyPk")).add(new BigDecimal(fiveM));
                                map.put("qjyLlhp", String.valueOf(qjyLlhp));
                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                                BigDecimal qjySjhp = qjyLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :qjyLlhp;
                                map.put("qjySjhp", String.valueOf(Math.round(Double.valueOf(qjySjhp.doubleValue()))));

                            } else if (name.getClassName().equals("酱料")) {
                                huopei.setJlThSum(String.valueOf(sum1));//酱料理论耗用数量小计
                                huopei.setJlRealSum(String.valueOf(sum2));//酱料实际耗用数量小计
                                huopei.setJlAmSum(String.valueOf(sum4));//酱料耗用金额分差小计
                                huopei.setJlNumSum(String.valueOf(sum3));//酱料耗用数量分差小计

                                //酱料盘亏
                                long jlPk = Math.round(Double.valueOf(huopei.getJlAmSum()));
                                jlPk = jlPk >= 0 ? 0 : jlPk;
                                //四舍五入取整
//                                map.put("jlPk", String.valueOf(Math.round(Double.valueOf(huopei.getJlAmSum()))));
                                map.put("jlPk", String.valueOf(jlPk));

                                BigDecimal jlAmSum = new BigDecimal(huopei.getJlAmSum());

                                //理论货赔 -> 盘亏+免赔+其他免赔
                                BigDecimal jlLlhp = new BigDecimal(map.get("jlPk")).add(new BigDecimal(fiveM));
                                map.put("jlLlhp", String.valueOf(jlLlhp));
                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                                BigDecimal jlSjhp = jlLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jlLlhp;
                                map.put("jlSjhp", String.valueOf(Math.round(Double.valueOf(jlSjhp.doubleValue()))));

                            } else if (name.getClassName().equals("酒水")) {
                                huopei.setJsThSum(String.valueOf(sum1));//酒水理论耗用数量小计
                                huopei.setJsRealSum(String.valueOf(sum2));//酒水实际耗用数量小计
                                huopei.setJsAmSum(String.valueOf(sum5));//酒水耗用金额分差小计
                                huopei.setJsNumSum(String.valueOf(sum3));//酒水耗用数量分差小计

                                //酒水盘亏
                                long jsPk = Math.round(Double.valueOf(huopei.getJsAmSum()));
                                jsPk = jsPk >= 0 ? 0 : jsPk;
                                //四舍五入取整
//                                map.put("jsPk", String.valueOf(Math.round(Double.valueOf(huopei.getJsAmSum()))));
                                map.put("jsPk", String.valueOf(jsPk));

                                BigDecimal jsAmSum = new BigDecimal(huopei.getJsAmSum());

                                //理论货赔 -> 盘亏+免赔+其他免赔(酒水没有免赔)
                                BigDecimal jsLlhp = new BigDecimal(map.get("jsPk"));
                                map.put("jsLlhp", String.valueOf(jsLlhp));
                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                                BigDecimal jsSjhp = jsLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jsLlhp;
                                map.put("jsSjhp", String.valueOf(Math.round(Double.valueOf(jsSjhp.doubleValue()))));

                            }else if (name.getClassName().equals("自采酒水")) {
                                huopei.setZcjsThSum(String.valueOf(sum1));//自采酒水理论耗用数量小计
                                huopei.setZcjsRealSum(String.valueOf(sum2));//自采酒水实际耗用数量小计
                                huopei.setZcjsAmSum(String.valueOf(sum5));//自采酒水耗用金额分差小计
                                huopei.setZcjsNumSum(String.valueOf(sum3));//自采酒水耗用数量分差小计

                                //自采酒水盘亏
                                long zcjsPk = Math.round(Double.valueOf(huopei.getZcjsAmSum()));
                                zcjsPk = zcjsPk >= 0 ? 0 : zcjsPk;
                                //四舍五入取整
//                                map.put("zcjsPk", String.valueOf(Math.round(Double.valueOf(huopei.getZcjsAmSum()))));
                                map.put("zcjsPk", String.valueOf(zcjsPk));

                                BigDecimal zcjsAmSum = new BigDecimal(huopei.getZcjsAmSum());

                                //理论货赔 -> 盘亏+免赔+其他免赔(酒水没有免赔)
                                BigDecimal zcjsLlhp = new BigDecimal(map.get("zcjsPk"));
                                map.put("zcjsLlhp", String.valueOf(zcjsLlhp));
                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                                BigDecimal zcjsSjhp = zcjsLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO : zcjsLlhp;
                                map.put("zcjsSjhp", String.valueOf(Math.round(Double.valueOf(zcjsSjhp.doubleValue()))));

                            }

                            if (param.getShopCode() != null) {
                                huopei.setShopCode(param.getShopCode());
                            } else if (huopeiList.size() != 0){
                                huopei.setShopCode(huopeiList.get(0).getShopCode());
                            }
                            huopei.setBeginTime(name.getBeginTime());
                            huopei.setEndTime(name.getEndTime());

                            baseMapper.update(huopei);

                        }
                    }
                }

                String shopCode = null;
                if (param.getShopCode() != null) {
                    shopCode = param.getShopCode();
                } else if (huopeiList.size() != 0){
                    shopCode = huopeiList.get(0).getShopCode();
                }
                if (shopCode != null){
                    //盘亏表新增相关数据
                    int count = btyCwPankuiMapper.count(shopCode, time.getEndTime());

                    //酒水盘亏 = 酒水 + 自采酒水 盘亏总计
                    int jspk = Integer.valueOf(ToolUtil.isNotEmpty(map.get("jsPk")) ? map.get("jsPk") : "0") +
                            Integer.valueOf(ToolUtil.isNotEmpty(map.get("zcjsPk")) ? map.get("zcjsPk") : "0");

                    //酒水理论货赔 盘亏+免赔+其他免赔(酒水没有免赔)
                    int jsLlhp = jspk;
                    //酒水实际货赔  -> 理论货赔金额大于0，取0; 小于0，取实际值
                    int jsSjhp = jsLlhp > 0 ? 0 : jsLlhp;

                    if (count == 0) {

                        BtyCwPankui btyCwPankui = new BtyCwPankui();
                        btyCwPankui.setShopCode(shopCode);
                        btyCwPankui.setQjyPk(ToolUtil.isNotEmpty(map.get("qjyPk")) ? map.get("qjyPk") : "0");//清江鱼盘亏
                        btyCwPankui.setJlPk(ToolUtil.isNotEmpty(map.get("jlPk")) ? map.get("jlPk") : "0");//酱料盘亏
                        btyCwPankui.setJsPk(String.valueOf(jspk));//酒水盘亏
                        btyCwPankui.setQjyMp(fiveM);//清江鱼免赔
                        btyCwPankui.setJlMp(fiveM);//酱料免赔
                        btyCwPankui.setJsMp("0");//酒水免赔
                        btyCwPankui.setQjyOther("0");//清江鱼其他免赔
                        btyCwPankui.setJlOther("0");//酱料其他免赔
                        btyCwPankui.setJsOther("0");//酒水其他免赔
                        btyCwPankui.setQjyLlhp(ToolUtil.isNotEmpty(map.get("qjyLlhp")) ? map.get("qjyLlhp") : "0");//清江鱼理论货赔
                        btyCwPankui.setJlLlhp(ToolUtil.isNotEmpty(map.get("jlLlhp")) ? map.get("jlLlhp") : "0");//酱料理论货赔
                        btyCwPankui.setJsLlhp(String.valueOf(jsLlhp));//酒水理论货赔
                        btyCwPankui.setQjySjhp(ToolUtil.isNotEmpty(map.get("qjySjhp")) ? map.get("qjySjhp") : "0");//清江鱼实际货赔
                        btyCwPankui.setJlSjhp(ToolUtil.isNotEmpty(map.get("jlSjhp")) ? map.get("jlSjhp") : "0");//酱料实际货赔
                        btyCwPankui.setJsSjhp(String.valueOf(jsSjhp));//酒水实际货赔
                        btyCwPankui.setQjyFine("0");//清江鱼罚款金额
                        btyCwPankui.setJlFine("0");//酱料罚款金额
                        btyCwPankui.setJsFine("0");//酒水罚款金额
                        btyCwPankui.setBeginTime(time.getBeginTime());//开始时间
                        btyCwPankui.setEndTime(time.getEndTime());//结束时间

                        //货赔合计=罚款金额+实际货赔
                        int heji = Integer.valueOf(ToolUtil.isNotEmpty(map.get("qjySjhp")) ? map.get("qjySjhp") : "0") +
                                Integer.valueOf(ToolUtil.isNotEmpty(map.get("jlSjhp")) ? map.get("jlSjhp") : "0") + jsSjhp;
                        btyCwPankui.setHeji(String.valueOf(heji));//货赔合计

                        btyCwPankuiMapper.insert(btyCwPankui);
                    }

                    //查询该店的盘亏信息
                    BtyCwPankui pankui = btyCwPankuiMapper.getPankui(shopCode, time.getEndTime());

                    //编辑数据库总计
                    BtyCwHuopei hp = new BtyCwHuopei();
                    hp.setShopCode(shopCode);//门店编号
                    hp.setBeginTime(time.getBeginTime());
                    hp.setEndTime(time.getEndTime());
                    hp.setTurnover(turnover);//营业额
                    hp.setFive(five);//营业额百分之五
                    hp.setTen(ten);//营业额百分之十
                    baseMapper.update(hp);

                    BtyCwHuopei result = new BtyCwHuopei();
                    result.setShopCode(shopCode);
                    result.setShopName("类别名称");
                    result.setScmClassCode("盘亏金额");
                    result.setClassName("免赔金额");
                    result.setProCode("其他免赔金额");
                    result.setProName("备注");
                    result.setSpec("理论货赔金额");
                    result.setUnit("实际货赔金额");
                    result.setPrice("罚款金额");
                    result.setThNum("货赔合计");
                    list.add(result);

                    BtyCwHuopei result1 = new BtyCwHuopei();
                    result1.setShopCode(shopCode);
                    result1.setShopName("清江鱼");
                    result1.setScmClassCode(pankui.getQjyPk());//盘亏->冻货小计->耗用金额分差小计
                    result1.setClassName(fiveM);//免赔->营业额5%
                    result1.setProCode(pankui.getQjyOther() == null ? "0" : pankui.getQjyOther());//其他免赔金额
                    result1.setProName(pankui.getQjyBz());//备注
                    result1.setSpec(pankui.getQjyLlhp());
                    result1.setUnit(pankui.getQjySjhp());//实际货赔金额->理论货赔金额大于0，取0;小于0，取实际值
                    result1.setPrice(pankui.getQjyFine() == null ? "0" : pankui.getQjyFine());//罚款金额
                    result1.setThNum(pankui.getHeji());//货赔合计
                    result1.setBeginTime(time.getBeginTime());
                    result1.setEndTime(time.getEndTime());
                    list.add(result1);

                    BtyCwHuopei result2 = new BtyCwHuopei();
                    result2.setShopCode(shopCode);
                    result2.setShopName("酱料");
                    result1.setScmClassCode(pankui.getJlPk());//盘亏->酱料小计->耗用金额分差小计
                    result2.setClassName(fiveM);//免赔->营业额5%
                    result2.setProCode(pankui.getJlOther() == null ? "0" : pankui.getJlOther());//其他免赔金额
                    result2.setProName(pankui.getJlBz());//备注
                    result2.setSpec(pankui.getJlLlhp());
                    result2.setUnit(pankui.getJlSjhp());//实际货赔金额->理论货赔金额大于0，取0;小于0，取实际值
                    result2.setPrice(pankui.getJlFine() == null ? "0" : pankui.getJlFine());//罚款金额
                    result2.setThNum(pankui.getHeji());//货赔合计
                    result2.setBeginTime(time.getBeginTime());
                    result2.setEndTime(time.getEndTime());
                    list.add(result2);

                    BtyCwHuopei result3 = new BtyCwHuopei();
                    result3.setShopCode(shopCode);
                    result3.setShopName("酒水");
                    result1.setScmClassCode(pankui.getJsPk());//盘亏->酒水小计->耗用金额分差小计
                    result3.setClassName(pankui.getJsMp());//免赔->酒水没有免赔
                    result3.setProCode(pankui.getJsOther() == null ? "0" : pankui.getJsOther());//其他免赔金额
                    result3.setProName(pankui.getJsBz());//备注
                    result3.setSpec(pankui.getJsLlhp());
                    result3.setUnit(pankui.getJsSjhp());//实际货赔金额->理论货赔金额大于0，取0;小于0，取实际值
                    result3.setPrice(pankui.getJsFine() == null ? "0" : pankui.getJsFine());//罚款金额
                    result3.setThNum(pankui.getHeji());//货赔合计
                    result3.setBeginTime(time.getBeginTime());
                    result3.setEndTime(time.getEndTime());
                    list.add(result3);

                    BtyCwHuopei huopei1 = new BtyCwHuopei();
                    list.add(huopei1);
                }
            }
        }


        return list;
    }

    /**
     * 货赔表详细（酒水与自采酒水分开显示）- pc
     * @param param
     * @param date
     * @return
     */
    @Override
    public List<BtyCwHuopei> getHuopei(BtyCwHuopei param, String date) {
        //要导出的list
        List<BtyCwHuopei> list = new ArrayList<>();

        //获取该店的货赔信息
        List<BtyCwHuopei> huopeiList = baseMapper.getHuopei(param,date);
        //查询该店的品相类别
        List<BtyCwHuopei> className = baseMapper.selectClassName(param);
        //获取所有时间段
        List<BtyCwHuopei> timeList = baseMapper.selectTime(param, date);

        BigDecimal turnover = BigDecimal.ZERO;
        BigDecimal five = BigDecimal.ZERO;
        BigDecimal ten = BigDecimal.ZERO;
        String fiveM = "";//免赔（营业额百分之五取整）

        if (CollectionUtil.isNotEmpty(huopeiList)) {
            //获取营业额
            turnover = yybbMapper.getYye(huopeiList.get(0).getShopName(), huopeiList.get(0).getBeginTime(), huopeiList.get(0).getEndTime());
            if (turnover == null){
                turnover = BigDecimal.ZERO;
            }
            turnover.setScale(2, BigDecimal.ROUND_HALF_UP);//截取两位

            five = turnover.multiply(new BigDecimal(0.0005)).setScale(2, BigDecimal.ROUND_HALF_UP);//营业额万分之五
            ten = turnover.multiply(new BigDecimal(0.001)).setScale(2, BigDecimal.ROUND_HALF_UP);//营业额万分之十
        }

        //遍历时间
        if (CollectionUtil.isNotEmpty(timeList)){
            for (BtyCwHuopei time : timeList) {
                int i = 0;
                Map<String, String> map = new HashMap();

                if (CollectionUtil.isNotEmpty(className)) {
                    //循环该店品相类别
                    for (BtyCwHuopei name : className) {
                        //循环的时间相同
//                        if (name.getBeginTime().equals(time.getBeginTime()) && name.getShopCode().equals(time.getShopCode())){
                        if (name.getEndTime().equals(time.getEndTime()) && name.getShopCode().equals(time.getShopCode())){

                            BigDecimal sum1 = new BigDecimal(0);//理论耗用数量
                            BigDecimal sum2 = new BigDecimal(0);//实际耗用数量
                            BigDecimal sum3 = new BigDecimal(0);//耗用数量分差
                            BigDecimal sum4 = new BigDecimal(0);//耗用金额分差
                            BigDecimal sum5 = new BigDecimal(0);//耗用金额分差(酒水，只取负数)

                            if (CollectionUtil.isNotEmpty(huopeiList)) {
                                //循环该店货赔信息
                                for (BtyCwHuopei huopei : huopeiList) {
                                    //品相类别相同
//                                    if (name.getClassName().equals(huopei.getClassName()) && time.getBeginTime().equals(huopei.getBeginTime())) {
                                    if (name.getClassName().equals(huopei.getClassName()) && time.getEndTime().equals(huopei.getEndTime())) {

//                                        修改序号
//                                        huopei.setNum(String.valueOf(i++));
//                                        baseMapper.updateNum(huopei.getNum(), huopei.getShopCode(), huopei.getProCode(), huopei.getEndTime());

                                        sum1 = sum1.add(huopei.getThNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getThNum()));
                                        sum2 = sum2.add(huopei.getRealNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getRealNum()));
                                        sum3 = sum3.add(huopei.getNumTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getNumTotal()));
                                        sum4 = sum4.add(huopei.getAmountTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));

                                        //酒水耗用金额分差小计 只取负数的合计
                                        if(name.getClassName().contains("酒水") && ToolUtil.isNotEmpty(huopei.getAmountTotal())){
                                            sum5 = sum5.add(new BigDecimal(huopei.getAmountTotal()).compareTo(BigDecimal.ZERO) >= 0 ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
                                        }

//                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                                        String dateSdf = "";
//
//                                        if(ToolUtil.isNotEmpty(param.getBeginTime())){
//                                            dateSdf = sdf.format(param.getBeginTime()).substring(0, 7);
//                                        }else if (ToolUtil.isNotEmpty(date)){
//                                            dateSdf = date;
//                                        }

                                        huopei.setTurnover(turnover);
                                        huopei.setFive(five);
                                        huopei.setTen(ten);

                                        list.add(huopei);

                                    }
                                }
                            }

                            name.setNum("小计");
                            name.setThNum(String.valueOf(sum1));//理论耗用数量
                            name.setRealNum(String.valueOf(sum2));//实际耗用数量
                            name.setNumTotal(String.valueOf(sum3));//耗用数量分差
                            if (name.getClassName().equals("酒水")){
                                name.setAmountTotal(String.valueOf(sum5));//耗用金额分差
                            }else {
                                name.setAmountTotal(String.valueOf(sum4));//耗用金额分差
                            }
                            list.add(name);

                            //修改数据库各小计
                            BtyCwHuopei huopei = new BtyCwHuopei();

                            fiveM = String.valueOf(Math.round(five.doubleValue()));//免赔（营业额百分之五取整）

                            if (name.getClassName().equals("冻货")) {
                                huopei.setDhThSum(String.valueOf(sum1));//冻货理论耗用数量小计
                                huopei.setDhRealSum(String.valueOf(sum2));//冻货实际耗用数量小计
                                huopei.setDhAmSum(String.valueOf(sum4));//冻货耗用金额分差小计
                                huopei.setDhNumSum(String.valueOf(sum3));//冻货耗用数量分差小计

                                //清江鱼盘亏
                                long qjyPk = Math.round(Double.valueOf(huopei.getDhAmSum()));
                                qjyPk = qjyPk >= 0 ? 0 : qjyPk;
                                //四舍五入取整
//                                map.put("qjyPk", String.valueOf(Math.round(Double.valueOf(huopei.getDhAmSum()))));
                                map.put("qjyPk", String.valueOf(qjyPk));

                                BigDecimal dhAmSum = new BigDecimal(huopei.getDhAmSum());
                                //理论货赔 -> 盘亏+免赔+其他免赔
                                BigDecimal qjyLlhp = new BigDecimal(map.get("qjyPk")).add(new BigDecimal(fiveM));
                                map.put("qjyLlhp", String.valueOf(qjyLlhp));
                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                                BigDecimal qjySjhp = qjyLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :qjyLlhp;
                                map.put("qjySjhp", String.valueOf(Math.round(Double.valueOf(qjySjhp.doubleValue()))));

                            } else if (name.getClassName().equals("酱料")) {
                                huopei.setJlThSum(String.valueOf(sum1));//酱料理论耗用数量小计
                                huopei.setJlRealSum(String.valueOf(sum2));//酱料实际耗用数量小计
                                huopei.setJlAmSum(String.valueOf(sum4));//酱料耗用金额分差小计
                                huopei.setJlNumSum(String.valueOf(sum3));//酱料耗用数量分差小计

                                //酱料盘亏
                                long jlPk = Math.round(Double.valueOf(huopei.getJlAmSum()));
                                jlPk = jlPk >= 0 ? 0 : jlPk;
                                //四舍五入取整
//                                map.put("jlPk", String.valueOf(Math.round(Double.valueOf(huopei.getJlAmSum()))));
                                map.put("jlPk", String.valueOf(jlPk));

                                BigDecimal jlAmSum = new BigDecimal(huopei.getJlAmSum());

                                //理论货赔 -> 盘亏+免赔+其他免赔
                                BigDecimal jlLlhp = new BigDecimal(map.get("jlPk")).add(new BigDecimal(fiveM));
                                map.put("jlLlhp", String.valueOf(jlLlhp));
                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                                BigDecimal jlSjhp = jlLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jlLlhp;
                                map.put("jlSjhp", String.valueOf(Math.round(Double.valueOf(jlSjhp.doubleValue()))));

                            } else if (name.getClassName().equals("酒水")) {
                                huopei.setJsThSum(String.valueOf(sum1));//酒水理论耗用数量小计
                                huopei.setJsRealSum(String.valueOf(sum2));//酒水实际耗用数量小计
                                huopei.setJsAmSum(String.valueOf(sum5));//酒水耗用金额分差小计
                                huopei.setJsNumSum(String.valueOf(sum3));//酒水耗用数量分差小计

                                //酒水盘亏
                                long jsPk = Math.round(Double.valueOf(huopei.getJsAmSum()));
                                jsPk = jsPk >= 0 ? 0 : jsPk;
                                //四舍五入取整
//                                map.put("jsPk", String.valueOf(Math.round(Double.valueOf(huopei.getJsAmSum()))));
                                map.put("jsPk", String.valueOf(jsPk));

                                BigDecimal jsAmSum = new BigDecimal(huopei.getJsAmSum());

                                //理论货赔 -> 盘亏+免赔+其他免赔(酒水没有免赔)
                                BigDecimal jsLlhp = new BigDecimal(map.get("jsPk"));
                                map.put("jsLlhp", String.valueOf(jsLlhp));
                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                                BigDecimal jsSjhp = jsLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jsLlhp;
                                map.put("jsSjhp", String.valueOf(Math.round(Double.valueOf(jsSjhp.doubleValue()))));

                            }else if (name.getClassName().equals("自采酒水")) {
                                huopei.setZcjsThSum(String.valueOf(sum1));//自采酒水理论耗用数量小计
                                huopei.setZcjsRealSum(String.valueOf(sum2));//自采酒水实际耗用数量小计
                                huopei.setZcjsAmSum(String.valueOf(sum5));//自采酒水耗用金额分差小计
                                huopei.setZcjsNumSum(String.valueOf(sum3));//自采酒水耗用数量分差小计

                                //自采酒水盘亏
                                long zcjsPk = Math.round(Double.valueOf(huopei.getZcjsAmSum()));
                                zcjsPk = zcjsPk >= 0 ? 0 : zcjsPk;
                                //四舍五入取整
//                                map.put("zcjsPk", String.valueOf(Math.round(Double.valueOf(huopei.getZcjsAmSum()))));
                                map.put("zcjsPk", String.valueOf(zcjsPk));

                                BigDecimal zcjsAmSum = new BigDecimal(huopei.getZcjsAmSum());

                                //理论货赔 -> 盘亏+免赔+其他免赔(酒水没有免赔)
                                BigDecimal zcjsLlhp = new BigDecimal(map.get("zcjsPk"));
                                map.put("zcjsLlhp", String.valueOf(zcjsLlhp));
                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                                BigDecimal zcjsSjhp = zcjsLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO : zcjsLlhp;
                                map.put("zcjsSjhp", String.valueOf(Math.round(Double.valueOf(zcjsSjhp.doubleValue()))));

                            }

                            if (param.getShopCode() != null) {
                                huopei.setShopCode(param.getShopCode());
                            } else if (huopeiList.size() != 0){
                                huopei.setShopCode(huopeiList.get(0).getShopCode());
                            }
                            huopei.setBeginTime(name.getBeginTime());
                            huopei.setEndTime(name.getEndTime());

                            baseMapper.update(huopei);

                        }
                    }
                }

                String shopCode = null;
                if (param.getShopCode() != null) {
                    shopCode = param.getShopCode();
                } else if (huopeiList.size() != 0){
                    shopCode = huopeiList.get(0).getShopCode();
                }
                if (shopCode != null){
                    //盘亏表新增相关数据
                    int count = btyCwPankuiMapper.count(shopCode, time.getEndTime());

                    //酒水盘亏 = 酒水 + 自采酒水 盘亏总计
                    int jspk = Integer.valueOf(ToolUtil.isNotEmpty(map.get("jsPk")) ? map.get("jsPk") : "0") +
                            Integer.valueOf(ToolUtil.isNotEmpty(map.get("zcjsPk")) ? map.get("zcjsPk") : "0");

                    //酒水理论货赔 盘亏+免赔+其他免赔(酒水没有免赔)
                    int jsLlhp = jspk;
                    //酒水实际货赔  -> 理论货赔金额大于0，取0; 小于0，取实际值
                    int jsSjhp = jsLlhp > 0 ? 0 : jsLlhp;

                    if (count == 0) {

                        BtyCwPankui btyCwPankui = new BtyCwPankui();
                        btyCwPankui.setShopCode(shopCode);
                        btyCwPankui.setQjyPk(ToolUtil.isNotEmpty(map.get("qjyPk")) ? map.get("qjyPk") : "0");//清江鱼盘亏
                        btyCwPankui.setJlPk(ToolUtil.isNotEmpty(map.get("jlPk")) ? map.get("jlPk") : "0");//酱料盘亏
                        btyCwPankui.setJsPk(String.valueOf(jspk));//酒水盘亏
                        btyCwPankui.setQjyMp(fiveM);//清江鱼免赔
                        btyCwPankui.setJlMp(fiveM);//酱料免赔
                        btyCwPankui.setJsMp("0");//酒水免赔
                        btyCwPankui.setQjyOther("0");//清江鱼其他免赔
                        btyCwPankui.setJlOther("0");//酱料其他免赔
                        btyCwPankui.setJsOther("0");//酒水其他免赔
                        btyCwPankui.setQjyLlhp(ToolUtil.isNotEmpty(map.get("qjyLlhp")) ? map.get("qjyLlhp") : "0");//清江鱼理论货赔
                        btyCwPankui.setJlLlhp(ToolUtil.isNotEmpty(map.get("jlLlhp")) ? map.get("jlLlhp") : "0");//酱料理论货赔
                        btyCwPankui.setJsLlhp(String.valueOf(jsLlhp));//酒水理论货赔
                        btyCwPankui.setQjySjhp(ToolUtil.isNotEmpty(map.get("qjySjhp")) ? map.get("qjySjhp") : "0");//清江鱼实际货赔
                        btyCwPankui.setJlSjhp(ToolUtil.isNotEmpty(map.get("jlSjhp")) ? map.get("jlSjhp") : "0");//酱料实际货赔
                        btyCwPankui.setJsSjhp(String.valueOf(jsSjhp));//酒水实际货赔
                        btyCwPankui.setQjyFine("0");//清江鱼罚款金额
                        btyCwPankui.setJlFine("0");//酱料罚款金额
                        btyCwPankui.setJsFine("0");//酒水罚款金额
                        btyCwPankui.setBeginTime(time.getBeginTime());//开始时间
                        btyCwPankui.setEndTime(time.getEndTime());//结束时间

                        //货赔合计=罚款金额+实际货赔
                        int heji = Integer.valueOf(ToolUtil.isNotEmpty(map.get("qjySjhp")) ? map.get("qjySjhp") : "0") +
                                Integer.valueOf(ToolUtil.isNotEmpty(map.get("jlSjhp")) ? map.get("jlSjhp") : "0") + jsSjhp;
                        btyCwPankui.setHeji(String.valueOf(heji));//货赔合计

                        btyCwPankuiMapper.insert(btyCwPankui);
                    }

                    //查询该店的盘亏信息
//                    BtyCwPankui pankui = btyCwPankuiMapper.getPankui(shopCode, time.getBeginTime());
                    BtyCwPankui pankui = btyCwPankuiMapper.getPankui(shopCode, time.getEndTime());

                    //编辑数据库总计
                    BtyCwHuopei hp = new BtyCwHuopei();
                    hp.setShopCode(shopCode);//门店编号
                    hp.setBeginTime(time.getBeginTime());
                    hp.setEndTime(time.getEndTime());
                    hp.setTurnover(turnover);//营业额
                    hp.setFive(five);//营业额百分之五
                    hp.setTen(ten);//营业额百分之十
                    baseMapper.update(hp);

                    BtyCwHuopei result = new BtyCwHuopei();
                    result.setShopCode(shopCode);
                    result.setShopName("类别名称");
                    result.setScmClassCode("盘亏金额");
                    result.setClassName("免赔金额");
                    result.setProCode("其他免赔金额");
                    result.setProName("备注");
                    result.setSpec("理论货赔金额");
                    result.setUnit("实际货赔金额");
                    result.setPrice("罚款金额");
                    result.setThNum("货赔合计");
                    list.add(result);

                    BtyCwHuopei result1 = new BtyCwHuopei();
                    result1.setShopCode(shopCode);
                    result1.setShopName("清江鱼");
                    result1.setScmClassCode(pankui.getQjyPk());//盘亏->冻货小计->耗用金额分差小计
                    result1.setClassName(fiveM);//免赔->营业额5%
                    //理论货赔金额
//                    BigDecimal qjyLlhp = new BigDecimal(map.get("qjyPk")).add(five).add(new BigDecimal(pankui.getQjyOther()));
                    result1.setProCode(pankui.getQjyOther() == null ? "0" : pankui.getQjyOther());//其他免赔金额
                    result1.setProName(pankui.getQjyBz());//备注
                    result1.setSpec(pankui.getQjyLlhp());//理论货赔金额->盘亏+免赔+其他免赔
                    result1.setUnit(pankui.getQjySjhp());//实际货赔金额->理论货赔金额大于0，取0;小于0，取实际值
                    result1.setPrice(pankui.getQjyFine() == null ? "0" : pankui.getQjyFine());//罚款金额
                    result1.setThNum(pankui.getHeji());//货赔合计

                    result1.setBeginTime(time.getBeginTime());
                    result1.setEndTime(time.getEndTime());
                    list.add(result1);

                    BtyCwHuopei result2 = new BtyCwHuopei();
                    result2.setShopCode(shopCode);
                    result2.setShopName("酱料");
                    result2.setScmClassCode(pankui.getJlPk());//盘亏->酱料小计->耗用金额分差小计
                    result2.setClassName(fiveM);//免赔->营业额5%
                    //理论货赔金额
//                    BigDecimal jlLlhp = new BigDecimal(map.get("jlPk")).add(five).add(new BigDecimal(pankui.getJlOther()));
                    result2.setProCode(pankui.getJlOther() == null ? "0" : pankui.getJlOther());//其他免赔金额
                    result2.setProName(pankui.getJlBz());//备注
                    result2.setSpec(pankui.getJlLlhp());//理论货赔金额->盘亏+免赔+其他免赔
                    result2.setUnit(pankui.getJlSjhp());//实际货赔金额->理论货赔金额大于0，取0;小于0，取实际值
                    result2.setPrice(pankui.getJlFine() == null ? "0" : pankui.getJlFine());//罚款金额
                    result2.setThNum(pankui.getHeji());//货赔合计

                    result2.setBeginTime(time.getBeginTime());
                    result2.setEndTime(time.getEndTime());
                    list.add(result2);

                    BtyCwHuopei result3 = new BtyCwHuopei();
                    result3.setShopCode(shopCode);
                    result3.setShopName("酒水");
                    result3.setScmClassCode(pankui.getJsPk());//盘亏->酒水小计->耗用金额分差小计
                    result3.setClassName(pankui.getJsMp());//免赔->酒水没有免赔
                    //理论货赔金额
//                    BigDecimal jsLlhp = new BigDecimal(map.get("jsPk")).add(five).add(new BigDecimal(pankui.getJsOther()));
                    result3.setProCode(pankui.getJsOther() == null ? "0" : pankui.getJsOther());//其他免赔金额
                    result3.setProName(pankui.getJsBz());//备注
                    result3.setSpec(pankui.getJsLlhp());//理论货赔金额->盘亏+免赔+其他免赔
                    result3.setUnit(pankui.getJsSjhp());//实际货赔金额->理论货赔金额大于0，取0;小于0，取实际值
                    result3.setPrice(pankui.getJsFine() == null ? "0" : pankui.getJsFine());//罚款金额
                    result3.setThNum(pankui.getHeji());//货赔合计

                    result3.setBeginTime(time.getBeginTime());
                    result3.setEndTime(time.getEndTime());
                    list.add(result3);


                    BtyCwHuopei huopei1 = new BtyCwHuopei();
                    list.add(huopei1);
                }
            }
        }


        return list;
    }

//    /**
//     * 货赔表详细（酒水与自采酒水归为一起显示）
//     * @param param
//     * @param date
//     * @return
//     */
//    @Override
//    public List<BtyCwHuopei> getHuopei(Huopei param, String date) {
//        //要导出的list
//        List<BtyCwHuopei> list = new ArrayList<>();
//
//        //获取该店的货赔信息
//        List<BtyCwHuopei> huopeiList = baseMapper.getHuopei(param,date);
//        //查询该店的品相类别
//        List<BtyCwHuopei> className = baseMapper.selectClassName(param);
//        //获取所有时间段
//        List<BtyCwHuopei> timeList = baseMapper.selectTime(param, date);
//
//        //遍历时间
//        if (CollectionUtil.isNotEmpty(timeList)){
//            for (BtyCwHuopei time : timeList) {
//                int i = 0;
//
//                BigDecimal turnover = BigDecimal.ZERO;
//                BigDecimal five = BigDecimal.ZERO;
//                BigDecimal ten = BigDecimal.ZERO;
//                String fiveM = "";;//免赔（营业额百分之五取整）
//
//                Map<String, String> map = new HashMap();
//
//                if (CollectionUtil.isNotEmpty(className)) {
//                    //循环该店品相类别
//                    for (BtyCwHuopei name : className) {
//                        //循环的时间相同
//                        if (name.getBeginTime().equals(time.getBeginTime()) && name.getShopCode().equals(time.getShopCode())){
//
//                            BigDecimal sum1 = new BigDecimal(0);//理论耗用数量
//                            BigDecimal sum2 = new BigDecimal(0);//实际耗用数量
//                            BigDecimal sum3 = new BigDecimal(0);//耗用数量分差
//                            BigDecimal sum4 = new BigDecimal(0);//耗用金额分差
//                            BigDecimal sum5 = new BigDecimal(0);//耗用金额分差(酒水，只取负数)
//
//                            if (CollectionUtil.isNotEmpty(huopeiList)) {
//                                //循环该店货赔信息
//                                for (BtyCwHuopei huopei : huopeiList) {
//                                    //品相类别相同,酒水与自采酒水归为一类
////                                    if (name.getClassName().equals(huopei.getClassName()) && time.getBeginTime().equals(huopei.getBeginTime())) {
//                                    if (((name.getClassName().equals(huopei.getClassName()) && !name.getClassName().contains("酒水")) ||
//                                        (name.getClassName().equals("酒水") && huopei.getClassName().contains("酒水")))
//                                         && time.getBeginTime().equals(huopei.getBeginTime())) {
//
//                                        //修改序号
//                                        huopei.setNum(String.valueOf(i++));
//                                        baseMapper.updateNum(huopei.getNum(), huopei.getShopCode(), huopei.getProCode(), huopei.getBeginTime());
//
//                                        sum1 = sum1.add(huopei.getThNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getThNum()));
//                                        sum2 = sum2.add(huopei.getRealNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getRealNum()));
//                                        sum3 = sum3.add(huopei.getNumTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getNumTotal()));
//                                        sum4 = sum4.add(huopei.getAmountTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
//
//                                        //酒水耗用金额分差小计 只取负数的合计
//                                        if(name.getClassName().contains("酒水") && ToolUtil.isNotEmpty(huopei.getAmountTotal())){
//                                            sum5 = sum5.add(new BigDecimal(huopei.getAmountTotal()).compareTo(BigDecimal.ZERO) >= 0 ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
//                                        }
//
//                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                                        String dateSdf = sdf.format(param.getBeginTime()).substring(0, 7);
//
//                                        //获取营业额
//                                        turnover = yybbMapper.getYye(huopei.getShopName(), dateSdf);
//
//                                        if (turnover == null){
//                                            turnover = BigDecimal.ZERO;
//                                        }
//                                        turnover.setScale(2, BigDecimal.ROUND_HALF_UP);//截取两位
//                                        huopei.setTurnover(turnover);
//
//                                        five = turnover.multiply(new BigDecimal(0.0005)).setScale(2, BigDecimal.ROUND_HALF_UP);//营业额万分之五
//                                        ten = turnover.multiply(new BigDecimal(0.001)).setScale(2, BigDecimal.ROUND_HALF_UP);//营业额万分之十
//                                        huopei.setFive(five);
//                                        huopei.setTen(ten);
//
//                                        list.add(huopei);
//
//                                    }
//                                }
//                            }
//                            //自采酒水与酒水归为一类
//                            if (!name.getClassName().equals("自采酒水")){
//                                name.setNum("小计");
//                                name.setThNum(String.valueOf(sum1));//理论耗用数量
//                                name.setRealNum(String.valueOf(sum2));//实际耗用数量
//                                name.setNumTotal(String.valueOf(sum3));//耗用数量分差
//                                if (name.getClassName().equals("酒水")){
//                                    name.setAmountTotal(String.valueOf(sum5));//耗用金额分差
//                                }else {
//                                    name.setAmountTotal(String.valueOf(sum4));//耗用金额分差
//                                }
//                                list.add(name);
//                            }
//
//                            //修改数据库各小计
//                            BtyCwHuopei huopei = new BtyCwHuopei();
//
//                            fiveM = String.valueOf(Math.round(five.doubleValue()));//免赔（营业额百分之五取整）
//
//                            if (name.getClassName().equals("冻货")) {
//                                huopei.setDhThSum(String.valueOf(sum1));//冻货理论耗用数量小计
//                                huopei.setDhRealSum(String.valueOf(sum2));//冻货实际耗用数量小计
//                                huopei.setDhAmSum(String.valueOf(sum4));//冻货耗用金额分差小计
//                                huopei.setDhNumSum(String.valueOf(sum3));//冻货耗用数量分差小计
//
//                                //四舍五入取整
//                                map.put("qjyPk", String.valueOf(Math.round(Double.valueOf(huopei.getDhAmSum()))));//清江鱼盘亏
//
//                                BigDecimal dhAmSum = new BigDecimal(huopei.getDhAmSum());
//                                //理论货赔 -> 盘亏+免赔+其他免赔
//                                BigDecimal qjyLlhp = new BigDecimal(map.get("qjyPk")).add(new BigDecimal(fiveM));
//                                map.put("qjyLlhp", String.valueOf(qjyLlhp));
//                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
//                                BigDecimal qjySjhp = qjyLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :qjyLlhp;
//                                map.put("qjySjhp", String.valueOf(Math.round(Double.valueOf(qjySjhp.doubleValue()))));
//
//                            } else if (name.getClassName().equals("酱料")) {
//                                huopei.setJlThSum(String.valueOf(sum1));//酱料理论耗用数量小计
//                                huopei.setJlRealSum(String.valueOf(sum2));//酱料实际耗用数量小计
//                                huopei.setJlAmSum(String.valueOf(sum4));//酱料耗用金额分差小计
//                                huopei.setJlNumSum(String.valueOf(sum3));//酱料耗用数量分差小计
//
//                                //四舍五入取整
//                                map.put("jlPk", String.valueOf(Math.round(Double.valueOf(huopei.getJlAmSum()))));//酱料盘亏
//
//                                BigDecimal jlAmSum = new BigDecimal(huopei.getJlAmSum());
//
//                                //理论货赔 -> 盘亏+免赔+其他免赔
//                                BigDecimal jlLlhp = new BigDecimal(map.get("jlPk")).add(new BigDecimal(fiveM));
//                                map.put("jlLlhp", String.valueOf(jlLlhp));
//                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
//                                BigDecimal jlSjhp = jlLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jlLlhp;
//                                map.put("jlSjhp", String.valueOf(Math.round(Double.valueOf(jlSjhp.doubleValue()))));
//
//                            } else if (name.getClassName().equals("酒水")) {
//                                huopei.setJsThSum(String.valueOf(sum1));//酒水理论耗用数量小计
//                                huopei.setJsRealSum(String.valueOf(sum2));//酒水实际耗用数量小计
//                                huopei.setJsAmSum(String.valueOf(sum5));//酒水耗用金额分差小计
//                                huopei.setJsNumSum(String.valueOf(sum3));//酒水耗用数量分差小计
//
//                                //四舍五入取整
//                                map.put("jsPk", String.valueOf(Math.round(Double.valueOf(huopei.getJsAmSum()))));//酒水盘亏
//
//                                BigDecimal jsAmSum = new BigDecimal(huopei.getJsAmSum());
//
//                                //理论货赔 -> 盘亏+免赔+其他免赔
//                                BigDecimal jsLlhp = new BigDecimal(map.get("jsPk")).add(new BigDecimal(fiveM));
//                                map.put("jsLlhp", String.valueOf(jsLlhp));
//                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
//                                BigDecimal jsSjhp = jsLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jsLlhp;
//                                map.put("jsSjhp", String.valueOf(Math.round(Double.valueOf(jsSjhp.doubleValue()))));
//
//                            }
//
//                            if (param.getShopCode() != null) {
//                                huopei.setShopCode(param.getShopCode());
//                            } else if (huopeiList.size() != 0){
//                                huopei.setShopCode(huopeiList.get(0).getShopCode());
//                            }
//                            huopei.setBeginTime(name.getBeginTime());
//
//                            baseMapper.update(huopei);
//
//                        }
//
//                    }
//                }
//
//                String shopCode = null;
//                if (param.getShopCode() != null) {
//                    shopCode = param.getShopCode();
//                } else if (huopeiList.size() != 0){
//                    shopCode = huopeiList.get(0).getShopCode();
//                }
//                if (shopCode != null){
//                    //盘亏表新增相关数据
//                    int count = btyCwPankuiMapper.count(shopCode, time.getBeginTime());
//
//                    if (count == 0) {
//                        BtyCwPankui pankui = new BtyCwPankui();
//                        pankui.setShopCode(shopCode);
//                        pankui.setQjyPk(ToolUtil.isNotEmpty(map.get("qjyPk")) ? map.get("qjyPk") : "0");//清江鱼盘亏
//                        pankui.setJlPk(ToolUtil.isNotEmpty(map.get("jlPk")) ? map.get("jlPk") : "0");//酱料盘亏
//                        pankui.setJsPk(ToolUtil.isNotEmpty(map.get("jsPk")) ? map.get("jsPk") : "0");//酒水盘亏
//                        pankui.setQjyMp(fiveM);//清江鱼免赔
//                        pankui.setJlMp(fiveM);//酱料免赔
//                        pankui.setJsMp("0");//酒水免赔
//                        pankui.setQjyOther("0");//清江鱼其他免赔
//                        pankui.setJlOther("0");//酱料其他免赔
//                        pankui.setJsOther("0");//酒水其他免赔
//                        pankui.setQjyLlhp(ToolUtil.isNotEmpty(map.get("qjyLlhp")) ? map.get("qjyLlhp") : "0");//清江鱼理论货赔
//                        pankui.setJlLlhp(ToolUtil.isNotEmpty(map.get("jlLlhp")) ? map.get("jlLlhp") : "0");//酱料理论货赔
//                        pankui.setJsLlhp(ToolUtil.isNotEmpty(map.get("jsLlhp")) ? map.get("jsLlhp") : "0");//酒水理论货赔
//                        pankui.setQjySjhp(ToolUtil.isNotEmpty(map.get("qjySjhp")) ? map.get("qjySjhp") : "0");//清江鱼实际货赔
//                        pankui.setJlSjhp(ToolUtil.isNotEmpty(map.get("jlSjhp")) ? map.get("jlSjhp") : "0");//酱料实际货赔
//                        pankui.setJsSjhp(ToolUtil.isNotEmpty(map.get("jsSjhp")) ? map.get("jsSjhp") : "0");//酒水实际货赔
//                        pankui.setQjyFine("0");//清江鱼罚款金额
//                        pankui.setJlFine("0");//酱料罚款金额
//                        pankui.setJsFine("0");//酒水罚款金额
//                        pankui.setBeginTime(time.getBeginTime());//开始时间
//                        pankui.setEndTime(time.getEndTime());//结束时间
//
//                        //货赔合计=罚款金额+实际货赔
//                        int heji = Integer.valueOf(ToolUtil.isNotEmpty(map.get("qjySjhp")) ? map.get("qjySjhp") : "0") +
//                                Integer.valueOf(ToolUtil.isNotEmpty(map.get("jlSjhp")) ? map.get("jlSjhp") : "0") +
//                                Integer.valueOf(ToolUtil.isNotEmpty(map.get("jsSjhp")) ? map.get("jsSjhp") : "0");
//                        pankui.setHeji(String.valueOf(heji));//货赔合计
//                        btyCwPankuiMapper.insert(pankui);
//
//                    }
//                    //查询该店的盘亏信息
//                    BtyCwPankui pankui = btyCwPankuiMapper.getPankui(shopCode, time.getBeginTime());
//
//                    //编辑数据库总计
//                    BtyCwHuopei hp = new BtyCwHuopei();
//                    hp.setShopCode(shopCode);//门店编号
//                    hp.setBeginTime(time.getBeginTime());
//                    hp.setTurnover(turnover);//营业额
//                    hp.setFive(five);//营业额百分之五
//                    hp.setTen(ten);//营业额百分之十
//                    baseMapper.update(hp);
//
//
//                    BtyCwHuopei result = new BtyCwHuopei();
//                    result.setNum("类别名称");
//                    result.setShopCode("盘亏金额");
//                    result.setShopName("免赔金额");
//                    result.setClassName("其他免赔金额");
//                    result.setProCode("备注");
//                    result.setProName("理论货赔金额");
//                    result.setSpec("罚款金额");
//                    result.setUnit("实际货赔金额");
//                    result.setPrice("货赔合计");
//                    list.add(result);
//
//                    //货赔合计 = 罚款金额 + 实际货赔
////                    BigDecimal hphj = new BigDecimal(pankui.getQjyFine()).add(new BigDecimal(map.get("qjySjhp")))
////                            .add(new BigDecimal(pankui.getJlFine())).add(new BigDecimal(map.get("jlSjhp")))
////                            .add(new BigDecimal(pankui.getJsFine())).add(new BigDecimal(map.get("jsSjhp")));
//
//                    BtyCwHuopei result1 = new BtyCwHuopei();
//                    result1.setNum("清江鱼");
//                    result1.setShopCode(pankui.getQjyPk());//盘亏->冻货小计->耗用金额分差小计
//                    result1.setShopName(fiveM);//免赔->营业额5%
//                    result1.setClassName(pankui.getQjyOther() == null ? "0" : pankui.getQjyOther());//其他免赔金额
//                    result1.setProCode(pankui.getQjyBz());//备注
//                    //理论货赔金额
////                    BigDecimal qjyLlhp = new BigDecimal(map.get("qjyPk")).add(five).add(new BigDecimal(pankui.getQjyOther()));
//                    result1.setProName(pankui.getQjyLlhp());//理论货赔金额->盘亏+免赔+其他免赔
//                    result1.setSpec(pankui.getQjyFine() == null ? "0" : pankui.getQjyFine());//罚款金额
//                    result1.setUnit(pankui.getQjySjhp());//实际货赔金额->理论货赔金额大于0，取0;小于0，取实际值
//
//                    result1.setPrice(pankui.getHeji());//货赔合计
//                    list.add(result1);
//
//                    BtyCwHuopei result2 = new BtyCwHuopei();
//                    result2.setNum("酱料");
//                    result2.setShopCode(pankui.getJlPk());//盘亏->酱料小计->耗用金额分差小计
//                    result2.setShopName(fiveM);//免赔->营业额5%
//                    result2.setClassName(pankui.getJlOther() == null ? "0" : pankui.getJlOther());//其他免赔金额
//                    result2.setProCode(pankui.getJlBz());//备注
//                    //理论货赔金额
////                    BigDecimal jlLlhp = new BigDecimal(map.get("jlPk")).add(five).add(new BigDecimal(pankui.getJlOther()));
//                    result2.setProName(pankui.getJlLlhp());//理论货赔金额->盘亏+免赔+其他免赔
//                    result2.setSpec(pankui.getJlFine() == null ? "0" : pankui.getJlFine());//罚款金额
//                    result2.setUnit(pankui.getJlSjhp());//实际货赔金额->理论货赔金额大于0，取0;小于0，取实际值
//
//                    result2.setPrice(pankui.getHeji());//货赔合计
//                    list.add(result2);
//
//                    BtyCwHuopei result3 = new BtyCwHuopei();
//                    result3.setNum("酒水");
//                    result3.setShopCode(pankui.getJsPk());//盘亏->酒水小计->耗用金额分差小计
//                    result3.setShopName(fiveM);//免赔->营业额5%
//                    result3.setClassName(pankui.getJsOther() == null ? "0" : pankui.getJsOther());//其他免赔金额
//                    result3.setProCode(pankui.getJsBz());//备注
//                    //理论货赔金额
////                    BigDecimal jsLlhp = new BigDecimal(map.get("jsPk")).add(five).add(new BigDecimal(pankui.getJsOther()));
//                    result3.setProName(pankui.getJsLlhp());//理论货赔金额->盘亏+免赔+其他免赔
//                    result3.setSpec(pankui.getJsFine() == null ? "0" : pankui.getJsFine());//罚款金额
//                    result3.setUnit(pankui.getJsSjhp());//实际货赔金额->理论货赔金额大于0，取0;小于0，取实际值
//
//                    result3.setPrice(pankui.getHeji());//货赔合计
//                    list.add(result3);
//
//
//                    BtyCwHuopei huopei1 = new BtyCwHuopei();
//                    list.add(huopei1);
//                }
//            }
//        }
//
//
//        return list;
//    }

    /**
     * 导出excel
     * pc - 各门店货赔详细信息
     * @return
     */
    @Override
    public ResponseEntity<byte[]> exportHp(HttpServletRequest request, HttpServletResponse response,
                                           String shopName, Date beginTime, String shopCode, String date, Date endTime) {

        BtyCwHuopei btyCwHuopei = new BtyCwHuopei();
        try {
            //TODO-1 要导出的数据内容
            btyCwHuopei.setBeginTime(beginTime);
            btyCwHuopei.setShopName(shopName);
            btyCwHuopei.setShopCode(shopCode);
            btyCwHuopei.setEndTime(endTime);

            //获取所有时间段
            List<BtyCwHuopei> timeList = baseMapper.selectTime(btyCwHuopei, date);

            //要导出的list
            List<BtyCwHuopei> list = new ArrayList<>();
            //获取数据库看有没有营业额
            BtyCwHuopei cwHuopei = baseMapper.getTurn(btyCwHuopei, date);
            //有数据 直接获取列表
            if (ToolUtil.isNotEmpty(cwHuopei) && ToolUtil.isNotEmpty(cwHuopei.getTurnover())){
                list = exportHuopei(btyCwHuopei,date);
                //计算
            }else {
                list = getHuopei(btyCwHuopei, date);
            }

//            List<BtyCwHuopei> list = exportHuopei(btyCwHuopei,date);
            BaseFrontController baseFrontController = new BaseFrontController();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            if (timeList.size() > 1){
                //文件名称
                String begin = sdf.format(timeList.get(0).getBeginTime());
                String begin1 = sdf.format(timeList.get(timeList.size()-1).getBeginTime());
                String time = begin.split("-")[1];
                String time1 = begin1.split("-")[1];
                String name = time + "月-" + time1 + "月货赔表";

                return baseFrontController.buildResponseEntity(export(list, timeList), name + ".xls");

            }else if (timeList.size() == 1){
                //文件名称
                String begin = sdf.format(list.get(0).getBeginTime());
                String time = begin.split("-")[1];
                String name = time + "月货赔表";
                return baseFrontController.buildResponseEntity(export(list, timeList), name + ".xls");

            } else {
                return baseFrontController.buildResponseEntity(null, null + ".xls");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 导出excel
     * app - 各门店货赔详细信息
     * @return
     */
    @Override
    public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response,
                                              String shopName, Date beginTime, String shopCode, String date, Date endTime) {

        BtyCwHuopei btyCwHuopei = new BtyCwHuopei();
        try {
            //TODO-1 要导出的数据内容
            btyCwHuopei.setBeginTime(beginTime);
            btyCwHuopei.setShopName(shopName);
            btyCwHuopei.setShopCode(shopCode);
            btyCwHuopei.setEndTime(endTime);

            //获取所有时间段
            List<BtyCwHuopei> timeList = baseMapper.selectTime(btyCwHuopei, date);

            //要导出的list
            List<BtyCwHuopei> list = new ArrayList<>();
            //获取数据库看有没有营业额
            BtyCwHuopei cwHuopei = baseMapper.getTurn(btyCwHuopei, date);
            //有数据 直接获取列表
            if (ToolUtil.isNotEmpty(cwHuopei) && ToolUtil.isNotEmpty(cwHuopei.getTurnover())){
//                list = exportHuopei(btyCwHuopei,date);
                list = exportHuopeiApp(btyCwHuopei,date);
                //计算
            }else {
//                list = getHuopei(btyCwHuopei, date);
                list = getHuopeiApp(btyCwHuopei, date);
            }

//            List<BtyCwHuopei> list = exportHuopei(btyCwHuopei,date);
            BaseFrontController baseFrontController = new BaseFrontController();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            if (timeList.size() > 1){
                //文件名称
                String begin = sdf.format(timeList.get(0).getBeginTime());
                String begin1 = sdf.format(timeList.get(timeList.size()-1).getBeginTime());
                String time = begin.split("-")[1];
                String time1 = begin1.split("-")[1];
                String name = time + "月-" + time1 + "月货赔表";

//                return baseFrontController.buildResponseEntity(export(list, timeList), name + ".xls");
                return baseFrontController.buildResponseEntity(exportApp(list, timeList), name + ".xls");

            }else if (timeList.size() == 1){
                //文件名称
                String begin = sdf.format(list.get(0).getBeginTime());
                String time = begin.split("-")[1];
                String name = time + "月货赔表";
//                return baseFrontController.buildResponseEntity(export(list, timeList), name + ".xls");
                return baseFrontController.buildResponseEntity(exportApp(list, timeList), name + ".xls");

            } else {
                return baseFrontController.buildResponseEntity(null, null + ".xls");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 导出excel样式 - pc
     *
     * @param list
     * @return
     */
    private InputStream export(List<BtyCwHuopei> list, List<BtyCwHuopei> timeList) {
        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式

        //TODO-2 每一列字段名
        String[] titles = new String[]{"", "门店编号", "门店名称", "品相类别编号", "品相类别名称", "品相编号", "品相名称", "规格", "单位",
                "非税成本单价", "销售数量", "实际耗用数量", "耗用数量分差", "耗用金额分差"};

        // 字段名所在表格的宽度，数量应与列字段名数量一致
        int[] ints = new int[]{1000, 3000, 5000, 5000, 5000, 3000, 5000, 5000, 3000, 3000, 3000, 3000, 3000, 3000};

        //TODO-3 设置总标题内容，没有可略过
        SXSSFRow row1 = sheet.createRow(0);
        SXSSFCell cell0 = row1.createCell(0);

        //合并单元格
        CellRangeAddress regionFist = new CellRangeAddress(0, 0, 0, 13); //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
        sheet.addMergedRegion(regionFist);
        //设置每一列的字段名

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String begin = sdf.format(timeList.get(0).getBeginTime());
        String end = sdf.format(timeList.get(timeList.size() - 1).getEndTime());
        BigDecimal turnover = BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP);
        if (ToolUtil.isNotEmpty(list)){
            turnover = list.get(0).getTurnover();
        }

        cell0.setCellValue("档口原料用量差异分析-货赔 (业务日期:" + begin + " 至 " + end + "营业额：" + turnover + ")");
        cell0.setCellStyle(header);

        CellStyle cellStyle1 = wb.createCellStyle();
        cellStyle1.setBorderBottom(BorderStyle.THIN);
        cellStyle1.setBorderLeft(BorderStyle.THIN);
        cellStyle1.setBorderRight(BorderStyle.THIN);
        cellStyle1.setBorderTop(BorderStyle.THIN);
        cellStyle1.setWrapText(true);// 设置自动换行
        cellStyle1.setAlignment(HorizontalAlignment.CENTER);// 设置单元格字体显示居中（左右方向）
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);// 设置单元格字体显示居中(上下方向)
        //设置单元格背景颜色
        cellStyle1.setFillPattern(FillPatternType.BIG_SPOTS);
        cellStyle1.setFillForegroundColor(IndexedColors.ROSE.getIndex());
        cellStyle1.setFillBackgroundColor(IndexedColors.ROSE.getIndex());


        //TODO-4 设置内容标题
        //内容的标题所在行
        int concentitleStartRow = 2;
        //设置表头样式
        ExcelFormatUtil.initContentTitleEX(sheet, header, concentitleStartRow, titles, ints);

        //TODO-5 从第contentStartRow行开始为内容数据
        int contentStartRow = 3;

        if (list != null && list.size() > 0) {

            int p = 0;
            for (int i = 0; i < list.size() - 1; i++) {

                BtyCwHuopei huopei = list.get(i);

                SXSSFRow row = sheet.createRow(contentStartRow + i - 1);
                int j = 0;
                int k = list.size() - 5;


                //序号
                SXSSFCell cell = row.createCell(j++);
                cell.setCellValue(huopei.getNum());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                // 门店编号
                cell = row.createCell(j++);
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellValue(huopei.getShopCode());
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                // 门店名称
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getShopName());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                //品相类别编号
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getScmClassCode());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                // 品项类别名称
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getClassName());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                // 品项编号
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getProCode());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                // 品项名称
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getProName());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                // 规格
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getSpec());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                // 单位
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getUnit());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                //非税单价
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getPrice());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                //理论耗用数量
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getThNum() == null ? "0" : huopei.getThNum().toString());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                //实际耗用数量
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getRealNum());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                //耗用数量分差
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getNumTotal());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                //耗用金额分差
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getAmountTotal());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }
//                cell.setCellStyle(content);

                if (i == list.size() - 2){
                    //合并单元格(货赔合计)
                    CellRangeAddress regioni = new CellRangeAddress(contentStartRow + list.size() - 5, contentStartRow + list.size() - 3, 10, 10); //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
                    sheet.addMergedRegion(regioni);
                }

            }

        }

        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null) {
                        inputStream1.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return inputStream1;
    }

    /**
     * 导出excel样式 - app
     *
     * @param list
     * @return
     */
    private InputStream exportApp(List<BtyCwHuopei> list, List<BtyCwHuopei> timeList) {
        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式

        //TODO-2 每一列字段名
        String[] titles = new String[]{"", "门店编号", "门店名称", "品相类别编号", "品相类别名称", "品相编号", "品相名称", "规格", "单位",
                "非税成本单价", "销售数量", "实际耗用数量", "耗用数量分差", "耗用金额分差"};

        // 字段名所在表格的宽度，数量应与列字段名数量一致
        int[] ints = new int[]{1000, 3000, 5000, 5000, 5000, 3000, 5000, 5000, 3000, 3000, 3000, 3000, 3000, 3000};

        //TODO-3 设置总标题内容，没有可略过
        SXSSFRow row1 = sheet.createRow(0);
        SXSSFCell cell0 = row1.createCell(0);

        //合并单元格
        CellRangeAddress regionFist = new CellRangeAddress(0, 0, 0, 13); //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
        sheet.addMergedRegion(regionFist);
        //设置每一列的字段名

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String begin = sdf.format(timeList.get(0).getBeginTime());
        String end = sdf.format(timeList.get(timeList.size() - 1).getEndTime());
        BigDecimal turnover = BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP);
        if (ToolUtil.isNotEmpty(list)){
            turnover = list.get(0).getTurnover();
        }

        cell0.setCellValue("档口原料用量差异分析-货赔 (业务日期:" + begin + " 至 " + end + "营业额：" + turnover + ")");
        cell0.setCellStyle(header);

        CellStyle cellStyle1 = wb.createCellStyle();
        cellStyle1.setBorderBottom(BorderStyle.THIN);
        cellStyle1.setBorderLeft(BorderStyle.THIN);
        cellStyle1.setBorderRight(BorderStyle.THIN);
        cellStyle1.setBorderTop(BorderStyle.THIN);
        cellStyle1.setWrapText(true);// 设置自动换行
        cellStyle1.setAlignment(HorizontalAlignment.CENTER);// 设置单元格字体显示居中（左右方向）
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);// 设置单元格字体显示居中(上下方向)
        //设置单元格背景颜色
        cellStyle1.setFillPattern(FillPatternType.BIG_SPOTS);
        cellStyle1.setFillForegroundColor(IndexedColors.ROSE.getIndex());
        cellStyle1.setFillBackgroundColor(IndexedColors.ROSE.getIndex());


        //TODO-4 设置内容标题
        //内容的标题所在行
        int concentitleStartRow = 2;
        //设置表头样式
        ExcelFormatUtil.initContentTitleEX(sheet, header, concentitleStartRow, titles, ints);

        //TODO-5 从第contentStartRow行开始为内容数据
        int contentStartRow = 3;

        if (list != null && list.size() > 0) {

            int p = 0;
            for (int i = 0; i < list.size() - 1; i++) {

                BtyCwHuopei huopei = list.get(i);

                SXSSFRow row = sheet.createRow(contentStartRow + i - 1);
                int j = 0;
                int k = list.size() - 5;


                //序号
                SXSSFCell cell = row.createCell(j++);
                cell.setCellValue(huopei.getNum());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                // 门店编号
                cell = row.createCell(j++);
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellValue(huopei.getShopCode());
                    cell.setCellStyle(content);
                }

                // 门店名称
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getShopName());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                //品相类别编号
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getScmClassCode());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                // 品项类别名称
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getClassName());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                // 品项编号
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getProCode());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                // 品项名称
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getProName());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                // 规格
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getSpec());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                // 单位
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getUnit());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                //非税单价
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getPrice());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                //理论耗用数量
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getThNum() == null ? "0" : huopei.getThNum().toString());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                //实际耗用数量
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getRealNum());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                //耗用数量分差
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getNumTotal());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                //耗用金额分差
                cell = row.createCell(j++);
                cell.setCellValue(huopei.getAmountTotal());
                if (k <= i){
                    cell.setCellStyle(cellStyle1);
                }else {
                    cell.setCellStyle(content);
                }

                if (i == list.size() - 2){
                    //合并单元格(货赔合计)
                    CellRangeAddress regioni = new CellRangeAddress(contentStartRow + list.size() - 5, contentStartRow + list.size() - 3, 10, 10); //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
                    sheet.addMergedRegion(regioni);
                }

            }

        }

        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null) {
                        inputStream1.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return inputStream1;
    }

    /**
     * 导出时货赔列表 - pc
     * @param param
     * @param date
     * @return
     */
    public List<BtyCwHuopei> exportHuopei(BtyCwHuopei param, String date) {

        List<BtyCwHuopei> huopeiList = new ArrayList<>();//获取该店的货赔信息
        List<BtyCwHuopei> className = new ArrayList<>();//查询该店的品相类别
        List<BtyCwHuopei> timeList = new ArrayList<>();//获取所有时间段

        //获取该店的货赔信息
        huopeiList = baseMapper.getHuopei(param, date);
        //查询该店的品相类别
        className = baseMapper.selectClassName(param);
        //获取所有时间段
        timeList = baseMapper.selectTime(param, date);
//        BigDecimal turnover = BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP);

        //要导出的list
        List<BtyCwHuopei> list = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(timeList)){
            for (BtyCwHuopei time : timeList) {

                if (CollectionUtil.isNotEmpty(className)) {
                    //循环该店品相类别
                    for (BtyCwHuopei name : className) {
                        //循环的时间相同
//                        if (name.getBeginTime().equals(time.getBeginTime()) && name.getShopCode().equals(time.getShopCode())){
                        if (name.getEndTime().equals(time.getEndTime()) && name.getShopCode().equals(time.getShopCode())){

                            BigDecimal sum1 = new BigDecimal(0);//理论耗用数量
                            BigDecimal sum2 = new BigDecimal(0);//实际耗用数量
                            BigDecimal sum3 = new BigDecimal(0);//耗用数量分差
                            BigDecimal sum4 = new BigDecimal(0);//耗用金额分差
                            BigDecimal sum5 = new BigDecimal(0);//耗用金额分差(酒水，只取负数)

                            if (CollectionUtil.isNotEmpty(huopeiList)) {

//                                turnover = huopeiList.get(0).getTurnover();

                                //循环该店货赔信息
                                for (BtyCwHuopei huopei : huopeiList) {
                                    //品相类别相同,店相同
//                                    if (name.getClassName().equals(huopei.getClassName()) && time.getBeginTime().equals(huopei.getBeginTime())
//                                            && huopei.getShopCode().equals(time.getShopCode())) {
                                    if (name.getClassName().equals(huopei.getClassName()) && time.getEndTime().equals(huopei.getEndTime())
                                            && huopei.getShopCode().equals(time.getShopCode())) {

                                        sum1 = sum1.add(huopei.getThNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getThNum()));
                                        sum2 = sum2.add(huopei.getRealNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getRealNum()));
                                        sum3 = sum3.add(huopei.getNumTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getNumTotal()));
                                        sum4 = sum4.add(huopei.getAmountTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
                                        //酒水耗用金额分差小计 只取负数的合计
                                        if(name.getClassName().contains("酒水") && ToolUtil.isNotEmpty(huopei.getAmountTotal())){
                                            sum5 = sum5.add(new BigDecimal(huopei.getAmountTotal()).compareTo(BigDecimal.ZERO) >= 0 ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
                                        }

                                        list.add(huopei);
                                    }
                                }
                            }

                            name.setNum("小计");
                            name.setThNum(String.valueOf(sum1));//理论耗用数量
                            name.setRealNum(String.valueOf(sum2));//实际耗用数量
                            name.setNumTotal(String.valueOf(sum3));//耗用数量分差
                            if (name.getClassName().equals("酒水")){
                                name.setAmountTotal(String.valueOf(sum5));//耗用金额分差
                            }else {
                                name.setAmountTotal(String.valueOf(sum4));//耗用金额分差
                            }
//                            name.setTurnover(turnover);
                            list.add(name);
                        }
                    }
                }

                String shopCode = null;
                if (param.getShopCode() != null) {
                    shopCode = param.getShopCode();
                } else if (huopeiList.size() != 0){
                    shopCode = time.getShopCode();
                }
                if (shopCode != null){

                    //查询该店的盘亏信息
//                    BtyCwPankui pankui = btyCwPankuiMapper.getPankui(shopCode, time.getBeginTime());
                    BtyCwPankui pankui = btyCwPankuiMapper.getPankui(shopCode, time.getEndTime());

                    BtyCwHuopei result = new BtyCwHuopei();
                    result.setShopCode(shopCode);
                    result.setShopName("类别名称");
                    result.setScmClassCode("盘亏金额");
                    result.setClassName("免赔金额");
                    result.setProCode("其他免赔金额");
                    result.setProName("备注");
                    result.setSpec("理论货赔金额");
                    result.setUnit("实际货赔金额");
                    result.setPrice("罚款金额");
                    result.setThNum("货赔合计");
                    list.add(result);

                    BtyCwHuopei result1 = new BtyCwHuopei();
                    result1.setShopCode(shopCode);
                    result1.setShopName("清江鱼");
                    result1.setScmClassCode(pankui.getQjyPk());
                    result1.setClassName(pankui.getQjyMp());
                    result1.setProCode(pankui.getQjyOther());
                    result1.setProName(pankui.getQjyBz());
                    result1.setSpec(pankui.getQjyLlhp());
                    result1.setUnit(pankui.getQjySjhp());
                    result1.setPrice(pankui.getQjyFine());
                    result1.setThNum(pankui.getHeji());
                    result1.setBeginTime(time.getBeginTime());
                    result1.setEndTime(time.getEndTime());
                    list.add(result1);

                    BtyCwHuopei result2 = new BtyCwHuopei();
                    result2.setShopCode(shopCode);
                    result2.setShopName("酱料");
                    result2.setScmClassCode(pankui.getJlPk());
                    result2.setClassName(pankui.getJlMp());
                    result2.setProCode(pankui.getJlOther());
                    result2.setProName(pankui.getJlBz());
                    result2.setSpec(pankui.getJlLlhp());
                    result2.setUnit(pankui.getJlSjhp());
                    result2.setPrice(pankui.getJlFine());
                    result2.setThNum(pankui.getHeji());
                    result2.setBeginTime(time.getBeginTime());
                    result2.setEndTime(time.getEndTime());
                    list.add(result2);

                    BtyCwHuopei result3 = new BtyCwHuopei();
                    result3.setShopCode(shopCode);
                    result3.setShopName("酒水");
                    result3.setScmClassCode(pankui.getJsPk());
                    result3.setClassName(pankui.getJsMp());
                    result3.setProCode(pankui.getJsOther());
                    result3.setProName(pankui.getJsBz());
                    result3.setSpec(pankui.getJsLlhp());
                    result3.setUnit(pankui.getJsSjhp());
                    result3.setPrice(pankui.getJsFine());
                    result3.setThNum(pankui.getHeji());
                    result3.setBeginTime(time.getBeginTime());
                    result3.setEndTime(time.getEndTime());
                    list.add(result3);

                    BtyCwHuopei huopei1 = new BtyCwHuopei();
                    list.add(huopei1);
                }
            }
        }

        return list;
    }

    /**
     * 导出时货赔列表 - app
     * @param param
     * @param date
     * @return
     */
    public List<BtyCwHuopei> exportHuopeiApp(BtyCwHuopei param, String date) {

        List<BtyCwHuopei> huopeiList = new ArrayList<>();//获取该店的货赔信息
        List<BtyCwHuopei> className = new ArrayList<>();//查询该店的品相类别
        List<BtyCwHuopei> timeList = new ArrayList<>();//获取所有时间段

        //获取该店的货赔信息
        huopeiList = baseMapper.getHuopei(param, date);
        //查询该店的品相类别
        className = baseMapper.selectClassName(param);
        //获取所有时间段
        timeList = baseMapper.selectTime(param, date);
//        BigDecimal turnover = BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP);

        //要导出的list
        List<BtyCwHuopei> list = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(timeList)){
            for (BtyCwHuopei time : timeList) {

                if (CollectionUtil.isNotEmpty(className)) {
                    //循环该店品相类别
                    for (BtyCwHuopei name : className) {
                        //循环的时间相同
//                        if (name.getBeginTime().equals(time.getBeginTime()) && name.getShopCode().equals(time.getShopCode())){
                        if (name.getEndTime().equals(time.getEndTime()) && name.getShopCode().equals(time.getShopCode())){

                            BigDecimal sum1 = new BigDecimal(0);//理论耗用数量
                            BigDecimal sum2 = new BigDecimal(0);//实际耗用数量
                            BigDecimal sum3 = new BigDecimal(0);//耗用数量分差
                            BigDecimal sum4 = new BigDecimal(0);//耗用金额分差
                            BigDecimal sum5 = new BigDecimal(0);//耗用金额分差(酒水，只取负数)

                            if (CollectionUtil.isNotEmpty(huopeiList)) {

//                                turnover = huopeiList.get(0).getTurnover();

                                //循环该店货赔信息
                                for (BtyCwHuopei huopei : huopeiList) {
                                    //品相类别相同,店相同
//                                    if (name.getClassName().equals(huopei.getClassName()) && time.getBeginTime().equals(huopei.getBeginTime())
//                                            && huopei.getShopCode().equals(time.getShopCode())) {
                                    if (name.getClassName().equals(huopei.getClassName()) && time.getEndTime().equals(huopei.getEndTime())
                                            && huopei.getShopCode().equals(time.getShopCode())) {

                                        sum1 = sum1.add(huopei.getThNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getThNum()));
                                        sum2 = sum2.add(huopei.getRealNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getRealNum()));
                                        sum3 = sum3.add(huopei.getNumTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getNumTotal()));
                                        sum4 = sum4.add(huopei.getAmountTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
                                        //酒水耗用金额分差小计 只取负数的合计
                                        if(name.getClassName().contains("酒水") && ToolUtil.isNotEmpty(huopei.getAmountTotal())){
                                            sum5 = sum5.add(new BigDecimal(huopei.getAmountTotal()).compareTo(BigDecimal.ZERO) >= 0 ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
                                        }

                                        list.add(huopei);
                                    }
                                }
                            }

                            name.setNum("小计");
                            name.setThNum(String.valueOf(sum1));//理论耗用数量
                            name.setRealNum(String.valueOf(sum2));//实际耗用数量
                            name.setNumTotal(String.valueOf(sum3));//耗用数量分差
                            if (name.getClassName().equals("酒水")){
                                name.setAmountTotal(String.valueOf(sum5));//耗用金额分差
                            }else {
                                name.setAmountTotal(String.valueOf(sum4));//耗用金额分差
                            }
//                            name.setTurnover(turnover);
                            list.add(name);
                        }
                    }
                }

                String shopCode = null;
                if (param.getShopCode() != null) {
                    shopCode = param.getShopCode();
                } else if (huopeiList.size() != 0){
                    shopCode = time.getShopCode();
                }
                if (shopCode != null){

                    //查询该店的盘亏信息
//                    BtyCwPankui pankui = btyCwPankuiMapper.getPankui(shopCode, time.getBeginTime());
                    BtyCwPankui pankui = btyCwPankuiMapper.getPankui(shopCode, time.getEndTime());

                    BtyCwHuopei result = new BtyCwHuopei();
                    result.setShopCode(shopCode);
                    result.setShopName("类别名称");
                    result.setScmClassCode("盘亏金额");
                    result.setClassName("免赔金额");
                    result.setProCode("其他免赔金额");
                    result.setProName("备注");
                    result.setSpec("理论货赔金额");
                    result.setUnit("实际货赔金额");
                    result.setPrice("罚款金额");
                    result.setThNum("货赔合计");
                    list.add(result);

                    BtyCwHuopei result1 = new BtyCwHuopei();
                    result1.setShopCode(shopCode);
                    result1.setShopName("清江鱼");
                    result1.setScmClassCode(pankui.getQjyPk());
                    result1.setClassName(pankui.getQjyMp());
                    result1.setProCode(pankui.getQjyOther());
                    result1.setProName(pankui.getQjyBz());
                    result1.setSpec(pankui.getQjyLlhp());
                    result1.setUnit(pankui.getQjySjhp());
                    result1.setPrice(pankui.getQjyFine());
                    result1.setThNum(pankui.getHeji());
                    result1.setBeginTime(time.getBeginTime());
                    result1.setEndTime(time.getEndTime());
                    list.add(result1);

                    BtyCwHuopei result2 = new BtyCwHuopei();
                    result2.setShopCode(shopCode);
                    result2.setShopName("酱料");
                    result2.setScmClassCode(pankui.getJlPk());
                    result2.setClassName(pankui.getJlMp());
                    result2.setProCode(pankui.getJlOther());
                    result2.setProName(pankui.getJlBz());
                    result2.setSpec(pankui.getJlLlhp());
                    result2.setUnit(pankui.getJlSjhp());
                    result2.setPrice(pankui.getJlFine());
                    result2.setThNum(pankui.getHeji());
                    result2.setBeginTime(time.getBeginTime());
                    result2.setEndTime(time.getEndTime());
                    list.add(result2);

                    BtyCwHuopei result3 = new BtyCwHuopei();
                    result3.setShopCode(shopCode);
                    result3.setShopName("酒水");
                    result3.setScmClassCode(pankui.getJsPk());
                    result3.setClassName(pankui.getJsMp());
                    result3.setProCode(pankui.getJsOther());
                    result3.setProName(pankui.getJsBz());
                    result3.setSpec(pankui.getJsLlhp());
                    result3.setUnit(pankui.getJsSjhp());
                    result3.setPrice(pankui.getJsFine());
                    result3.setThNum(pankui.getHeji());
                    result3.setBeginTime(time.getBeginTime());
                    result3.setEndTime(time.getEndTime());
                    list.add(result3);

                    BtyCwHuopei huopei1 = new BtyCwHuopei();
                    list.add(huopei1);
                }
            }
        }

        return list;
    }

    /**
     * 编辑接口
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData editHuopei(BtyCwHuopei param) {
        BtyCwPankui btyCwPankui = new BtyCwPankui();

        //查询盘亏
        BtyCwPankui caiwuPankui = btyCwPankuiMapper.getPankui(param.getShopCode(),param.getEndTime());

            //计算合计
            if (param.getShopName() != null && param.getShopName().equals("清江鱼")) {

//                btyCwPankui.setQjyOther(param.getProName());//清江鱼其他免赔
                btyCwPankui.setQjyOther(param.getProCode());//清江鱼其他免赔
//                btyCwPankui.setQjyBz(param.getSpec());//清江鱼备注
                btyCwPankui.setQjyBz(param.getProName());//清江鱼备注
//                btyCwPankui.setQjyFine(param.getThNum());//清江鱼罚款
                btyCwPankui.setQjyFine(param.getPrice());//清江鱼罚款

                BigDecimal qjyPk = caiwuPankui.getQjyPk() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getQjyPk()).setScale(2, BigDecimal.ROUND_HALF_UP);//清江鱼盘亏
                BigDecimal qjyMp = caiwuPankui.getQjyMp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getQjyMp()).setScale(2, BigDecimal.ROUND_HALF_UP);//清江鱼免赔

                //清江鱼理论货赔 = 盘亏+免赔+其他免赔
                BigDecimal qjyLlHp = qjyPk.add(qjyMp).add(new BigDecimal(btyCwPankui.getQjyOther())).setScale(2, BigDecimal.ROUND_HALF_UP);
                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                BigDecimal qjySjhp = qjyLlHp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO : qjyLlHp;
                qjySjhp.setScale(2, BigDecimal.ROUND_HALF_UP);

                btyCwPankui.setQjyLlhp(String.valueOf(qjyLlHp));
                btyCwPankui.setQjySjhp(String.valueOf(qjySjhp));

                //货赔合计 = 罚款金额+实际货赔
                BigDecimal hphj = new BigDecimal(btyCwPankui.getQjyFine()).add(new BigDecimal(btyCwPankui.getQjySjhp()))
                        .add(new BigDecimal(caiwuPankui.getJlFine())).add(new BigDecimal(caiwuPankui.getJlSjhp()))
                        .add(new BigDecimal(caiwuPankui.getJsFine())).add(new BigDecimal(caiwuPankui.getJsSjhp()));
                hphj.setScale(2, BigDecimal.ROUND_HALF_UP);

                btyCwPankui.setHeji(String.valueOf(hphj));//货赔合计

            } else if (param.getShopName() != null && param.getShopName().equals("酱料")) {

                btyCwPankui.setJlOther(param.getProCode());//酱料其他免赔
                btyCwPankui.setJlBz(param.getProName());//酱料备注
                btyCwPankui.setJlFine(param.getPrice());//酱料罚款

                BigDecimal jlPk = caiwuPankui.getJlPk() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getJlPk()).setScale(2, BigDecimal.ROUND_HALF_UP);//酱料盘亏
                BigDecimal jlMp = caiwuPankui.getJlMp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getJlMp()).setScale(2, BigDecimal.ROUND_HALF_UP);//酱料免赔

                //酱料理论货赔 = 盘亏+免赔+其他免赔
                BigDecimal jlLlHp = jlPk.add(jlMp).add(new BigDecimal(btyCwPankui.getJlOther())).setScale(2, BigDecimal.ROUND_HALF_UP);
                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                BigDecimal jlSjhp = jlLlHp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO : jlLlHp;
                jlSjhp.setScale(2, BigDecimal.ROUND_HALF_UP);

                btyCwPankui.setJlLlhp(String.valueOf(jlLlHp));
                btyCwPankui.setJlSjhp(String.valueOf(jlSjhp));

                //货赔合计 = 罚款金额+实际货赔
                BigDecimal hphj = new BigDecimal(caiwuPankui.getQjyFine()).add(new BigDecimal(caiwuPankui.getQjySjhp()))
                        .add(new BigDecimal(btyCwPankui.getJlFine())).add(new BigDecimal(btyCwPankui.getJlSjhp()))
                        .add(new BigDecimal(caiwuPankui.getJsFine())).add(new BigDecimal(caiwuPankui.getJsSjhp()));
                hphj.setScale(2, BigDecimal.ROUND_HALF_UP);

                btyCwPankui.setHeji(String.valueOf(hphj));//货赔合计

            } else if (param.getShopName() != null && param.getShopName().equals("酒水")) {

                btyCwPankui.setJsOther(param.getProCode());//酒水其他免赔
                btyCwPankui.setJsBz(param.getProName());//酒水备注
                btyCwPankui.setJsFine(param.getPrice());//酒水罚款

                BigDecimal jsPk = caiwuPankui.getJsPk() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getJsPk()).setScale(2, BigDecimal.ROUND_HALF_UP);//酒水盘亏
                BigDecimal jsMp = caiwuPankui.getJsMp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getJsMp()).setScale(2, BigDecimal.ROUND_HALF_UP);//酒水免赔

                //酒水理论货赔 = 盘亏+免赔+其他免赔
                BigDecimal jsLlHp = jsPk.add(jsMp).add(new BigDecimal(btyCwPankui.getJsOther())).setScale(2, BigDecimal.ROUND_HALF_UP);
                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                BigDecimal jsSjhp = jsLlHp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO : jsLlHp;
                jsSjhp.setScale(2, BigDecimal.ROUND_HALF_UP);

                btyCwPankui.setJsLlhp(String.valueOf(jsLlHp));
                btyCwPankui.setJsSjhp(String.valueOf(jsSjhp));

                //货赔合计 = 罚款金额+实际货赔
                BigDecimal hphj = new BigDecimal(caiwuPankui.getQjyFine()).add(new BigDecimal(caiwuPankui.getQjySjhp()))
                        .add(new BigDecimal(caiwuPankui.getJlFine())).add(new BigDecimal(caiwuPankui.getJlSjhp()))
                        .add(new BigDecimal(btyCwPankui.getJsFine())).add(new BigDecimal(btyCwPankui.getJsSjhp()));
                hphj.setScale(2, BigDecimal.ROUND_HALF_UP);

                btyCwPankui.setHeji(String.valueOf(hphj));//货赔合计

            }

            btyCwPankui.setShopCode(param.getShopCode());//门店编号
            btyCwPankui.setBeginTime(param.getBeginTime());
            btyCwPankui.setEndTime(param.getEndTime());

            btyCwPankuiMapper.update(btyCwPankui);

        return ResponseData.success();
    }

    /**
     * 店名列表
     * @return
     */
    @Override
    public List dmList() {
        //当前登陆者姓名
        String name = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();

        List<String> list = new ArrayList<>();

        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
//            list = this.baseMapper.dmList(null);
            list = baseMapper.dmListA();

        }else if (roleNames.contains("会计")){

            //获取成本会计所对应店名
            list = this.baseMapper.dmList(name);

        }
        return list;
    }

    /**
     * 同步酒水卖价
     * @return
     */
    @Override
    public ResponseData editJsmj(String date) {
        //获取酒水卖价
        List<Map> list = cwJsMapper.getJsList(date);
        //修改货赔表酒水卖价
        if(ToolUtil.isNotEmpty(list)){
            for (Map map : list) {
                String month = map.get("date").toString();
                BtyCwHuopei cwHuopei = new BtyCwHuopei();
                cwHuopei.setPrice(map.get("price").toString());//酒水价格
                cwHuopei.setProCode(map.get("pro_code").toString());//品项编号
                baseMapper.editPrice(cwHuopei,month);

                //获取修改卖价的主键ID
                List<BtyCwHuopei> hpList = baseMapper.getIdList(map.get("pro_code").toString(),month);
                if (ToolUtil.isNotEmpty(hpList)){
                    for (BtyCwHuopei huopei : hpList) {
                        BigDecimal price = new BigDecimal(huopei.getPrice());
                        BigDecimal num = new BigDecimal(huopei.getNumTotal());

                        BigDecimal amountTotal = price.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
                        huopei.setAmountTotal(amountTotal.toString());
                    }

                    if (ToolUtil.isNotEmpty(hpList)){
                        //每150条保存一次
                        for(int i = 0; i < hpList.size();){
                            int i2 = (i + 250);
                            i2 = i2 > hpList.size() ? hpList.size() : i2;
                            List<BtyCwHuopei> sub = hpList.subList(i, i2);
                            //修改数据库城市
                            baseMapper.editAmount(sub);
                            i = i2;
                        }
                    }

//                    baseMapper.editAmount(hpList);
                }

                editPankui(hpList);//计算盘亏数据
            }
        }

        return ResponseData.success();
    }

    /**
     * 计算盘亏数据
     * @param list
     * @return
     */
    @Override
    public ResponseData editPankui(List<BtyCwHuopei> list){
        if (ToolUtil.isNotEmpty(list)){
            for (BtyCwHuopei huopei : list) {

                //获取该店的盘亏数据
                BtyCwPankui pankui = btyCwPankuiMapper.getPankui(huopei.getShopCode(), huopei.getEndTime());

                if (ToolUtil.isNotEmpty(pankui)){

                    //获取货赔表该店酒水数据(负数合计)
                    BigDecimal jsAmount = baseMapper.jsAmount(huopei);
                    if (ToolUtil.isEmpty(jsAmount)){
                        jsAmount = BigDecimal.ZERO;
                    }

                    //获取货赔表该店自采酒水数据(负数合计)
                    BigDecimal zcjsAmount = baseMapper.zcjsAmount(huopei);
                    if (ToolUtil.isEmpty(zcjsAmount)){
                        zcjsAmount = BigDecimal.ZERO;
                    }

                    if (huopei.getClassName().equals("酒水")){

                        //此酒水的耗用金额分差
                        BigDecimal jsPr = new BigDecimal(huopei.getNumTotal()).multiply(new BigDecimal(huopei.getPrice()));
                        jsPr = jsPr.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO : jsPr;

                        //酒水耗用金额分差小计（除此酒水外酒水耗用金额分差之和 + 此酒水的耗用金额分差）
                        jsAmount = jsAmount.add(jsPr);

                        huopei.setJsAmSum(jsAmount.toString());
                    }

                    if (huopei.getClassName().equals("自采酒水")){

                        //此酒水的耗用金额分差
                        BigDecimal zcjsPr = new BigDecimal(huopei.getNumTotal()).multiply(new BigDecimal(huopei.getPrice()));
                        zcjsPr = zcjsPr.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO : zcjsPr;

                        //自采酒水耗用金额分差小计
                        zcjsAmount = zcjsAmount.add(zcjsPr);
                        huopei.setZcjsAmSum(zcjsAmount.toString());
                    }

                    baseMapper.updateJs(huopei);//修改货赔表数据

                    BigDecimal jsPk = jsAmount.add(zcjsAmount).setScale(0, BigDecimal.ROUND_HALF_UP);
                    pankui.setJsPk(jsPk.toString());

                    //计算酒水理论货赔（等于盘亏+免赔+其他免赔）
                    BigDecimal jsLlhp = jsPk.add(new BigDecimal(pankui.getJsMp())).add(new BigDecimal(pankui.getJsOther())).setScale(0, BigDecimal.ROUND_HALF_UP);
                    pankui.setJsLlhp(jsLlhp.toString());

                    //计算酒水实际货赔（如果理论货赔金额大于0，取0；小于0，取实际值）
                    BigDecimal jsSjhp = jsLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jsLlhp;
                    pankui.setJsSjhp(jsSjhp.toString());

                    //计算货赔合计（货赔合计=罚款金额+实际货赔）
                    BigDecimal hphj = new BigDecimal(pankui.getQjyFine()).add(new BigDecimal(pankui.getQjySjhp()))
                            .add(new BigDecimal(pankui.getJlFine())).add(new BigDecimal(pankui.getJlSjhp()))
                            .add(new BigDecimal(pankui.getJsFine())).add(jsSjhp);
                    hphj.setScale(0, BigDecimal.ROUND_HALF_UP);
                    pankui.setHeji(hphj.toString());

                    btyCwPankuiMapper.update(pankui);
                }

            }
        }

        return ResponseData.success();
    }

    /**
     * 导出列表
     * @param date
     * @return
     */
    @Override
    public List<BtyCwHuopeiResult> exportList(String date) {

        //当前登陆者姓名
        String name = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        List<BtyCwHuopeiResult> list = new ArrayList<>();

        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
            list = this.baseMapper.exportList(date, null);

        }else if (roleNames.contains("会计")){

            //获取成本会计所对应店名
            List<String> dm = this.baseMapper.dmList(name);
            list = this.baseMapper.exportList(date, dm);

        }
        return list;
    }

    /**
     * 同步单店酒水价格
     * @param date
     * @param shopCode
     * @return
     */
    @Override
    public ResponseData editDdjs(String date, String shopCode) {
        //获取酒水卖价
        List<Map> list = cwJsMapper.getJsList(date);
        //修改货赔表酒水卖价
        if(ToolUtil.isNotEmpty(list)){
            for (Map map : list) {
                String month = map.get("date").toString();
                BtyCwHuopei cwHuopei = new BtyCwHuopei();
                cwHuopei.setPrice(map.get("price").toString());//酒水价格
                cwHuopei.setProCode(map.get("pro_code").toString());//品项编号
                cwHuopei.setShopCode(shopCode);//门店编号
                baseMapper.editJsPrice(cwHuopei,month);

                //获取修改卖价的主键ID
                List<BtyCwHuopei> hpList = baseMapper.getJsIdList(map.get("pro_code").toString(), month, shopCode);
                if (ToolUtil.isNotEmpty(hpList)){
                    for (BtyCwHuopei huopei : hpList) {
                        BigDecimal price = new BigDecimal(huopei.getPrice());
                        BigDecimal num = new BigDecimal(huopei.getNumTotal());

                        BigDecimal amountTotal = price.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
                        huopei.setAmountTotal(amountTotal.toString());
                    }
                    baseMapper.editAmount(hpList);
                }

                editPankui(hpList);//计算盘亏数据
            }
        }

        return ResponseData.success();
    }


    /**
     * 计算货赔合计
     * @param date
     * @return
     */
    @Override
    public ResponseData editHp(String date) {

        //当前登陆者姓名
        String userName = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        List<String> dm = new ArrayList<>();
        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
            dm = null;
        }else if (roleNames.contains("成本会计")){
            dm = this.baseMapper.getDm(null, userName,null);
        }
        //获取此日期没有货赔的全部店
        List<BtyCwHuopei> hpList = baseMapper.getDmList(date, dm);

        //获取该日期没有货赔店的各小计
        List<Map> xjList = baseMapper.getXjList(date);

        Map<String, String> pkMap = new HashMap();
        BigDecimal turnover = BigDecimal.ZERO;//营业额
        BigDecimal five = BigDecimal.ZERO;//营业额百分之五
        BigDecimal ten = BigDecimal.ZERO;//营业额百分之十
        String fiveM = "";//免赔（营业额百分之五取整）

        if (ToolUtil.isNotEmpty(hpList)){
            for (BtyCwHuopei cwHuopei : hpList) {

                //获取营业额
                turnover = yybbMapper.getYye(cwHuopei.getShopName(), cwHuopei.getBeginTime(), cwHuopei.getEndTime());
                if (turnover == null){
                    turnover = BigDecimal.ZERO;
                }
                turnover.setScale(2, BigDecimal.ROUND_HALF_UP);//截取两位
                cwHuopei.setTurnover(turnover);

                five = turnover.multiply(new BigDecimal(0.0005)).setScale(2, BigDecimal.ROUND_HALF_UP);//营业额万分之五
                ten = turnover.multiply(new BigDecimal(0.001)).setScale(2, BigDecimal.ROUND_HALF_UP);//营业额万分之十
                cwHuopei.setFive(five);
                cwHuopei.setTen(ten);
                fiveM = String.valueOf(Math.round(five.doubleValue()));//免赔（营业额百分之五取整）

                for (Map map : xjList) {//各小计赋值
                    if (ToolUtil.isNotEmpty(map) && map.get("shop_code").equals(cwHuopei.getShopCode())){
                        if (map.get("class_name").equals("冻货")){
                            cwHuopei.setDhThSum(map.get("th_num").toString());//冻货理论耗用数量小计
                            cwHuopei.setDhRealSum(map.get("real_num").toString());//冻货实际耗用数量小计
                            cwHuopei.setDhAmSum(map.get("amount_total").toString());//冻货耗用金额分差小计
                            cwHuopei.setDhNumSum(map.get("num_total").toString());//冻货耗用数量分差小计

                            //清江鱼盘亏
                            long qjyPk = Math.round(Double.valueOf(cwHuopei.getDhAmSum()));
                            qjyPk = qjyPk >= 0 ? 0 : qjyPk;
                            //四舍五入取整
                            pkMap.put("qjyPk", String.valueOf(qjyPk));

                            //理论货赔 -> 盘亏+免赔+其他免赔
                            BigDecimal qjyLlhp = new BigDecimal(pkMap.get("qjyPk")).add(new BigDecimal(fiveM));
                            pkMap.put("qjyLlhp", String.valueOf(qjyLlhp));
                            //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                            BigDecimal qjySjhp = qjyLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :qjyLlhp;
                            pkMap.put("qjySjhp", String.valueOf(Math.round(Double.valueOf(qjySjhp.doubleValue()))));
                        }

                        if (map.get("class_name").equals("酱料")){
                            cwHuopei.setJlThSum(map.get("th_num").toString());//酱料理论耗用数量小计
                            cwHuopei.setJlRealSum(map.get("real_num").toString());//酱料实际耗用数量小计
                            cwHuopei.setJlAmSum(map.get("amount_total").toString());//酱料耗用金额分差小计
                            cwHuopei.setJlNumSum(map.get("num_total").toString());//酱料耗用数量分差小计

                            //酱料盘亏
                            long jlPk = Math.round(Double.valueOf(cwHuopei.getJlAmSum()));
                            jlPk = jlPk >= 0 ? 0 : jlPk;
                            //四舍五入取整
                            pkMap.put("jlPk", String.valueOf(jlPk));

                            //理论货赔 -> 盘亏+免赔+其他免赔
                            BigDecimal jlLlhp = new BigDecimal(pkMap.get("jlPk")).add(new BigDecimal(fiveM));
                            pkMap.put("jlLlhp", String.valueOf(jlLlhp));
                            //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                            BigDecimal jlSjhp = jlLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jlLlhp;
                            pkMap.put("jlSjhp", String.valueOf(Math.round(Double.valueOf(jlSjhp.doubleValue()))));
                        }

                        if (map.get("class_name").equals("酒水")){
                            cwHuopei.setJsThSum(map.get("th_num").toString());//酒水理论耗用数量小计
                            cwHuopei.setJsRealSum(map.get("real_num").toString());//酒水实际耗用数量小计
                            cwHuopei.setJsAmSum(map.get("amount_total").toString());//酒水耗用金额分差小计
                            cwHuopei.setJsNumSum(map.get("num_total").toString());//酒水耗用数量分差小计

                            //酒水盘亏
                            long jsPk = Math.round(Double.valueOf(cwHuopei.getJsAmSum()));
                            jsPk = jsPk >= 0 ? 0 : jsPk;
                            //四舍五入取整
                            pkMap.put("jsPk", String.valueOf(jsPk));

                            //理论货赔 -> 盘亏+免赔+其他免赔(酒水没有免赔)
                            BigDecimal jsLlhp = new BigDecimal(pkMap.get("jsPk"));
                            pkMap.put("jsLlhp", String.valueOf(jsLlhp));
                            //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                            BigDecimal jsSjhp = jsLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jsLlhp;
                            pkMap.put("jsSjhp", String.valueOf(Math.round(Double.valueOf(jsSjhp.doubleValue()))));
                        }

                        if (map.get("class_name").equals("自采酒水")){
                            cwHuopei.setZcjsThSum(map.get("th_num").toString());//自采酒水理论耗用数量小计
                            cwHuopei.setZcjsRealSum(map.get("real_num").toString());//自采酒水实际耗用数量小计
                            cwHuopei.setZcjsAmSum(map.get("amount_total").toString());//自采酒水耗用金额分差小计
                            cwHuopei.setZcjsNumSum(map.get("num_total").toString());//自采酒水耗用数量分差小计

                            //自采酒水盘亏
                            long zcjsPk = Math.round(Double.valueOf(cwHuopei.getZcjsAmSum()));
                            zcjsPk = zcjsPk >= 0 ? 0 : zcjsPk;
                            //四舍五入取整
                            pkMap.put("zcjsPk", String.valueOf(zcjsPk));

                            //理论货赔 -> 盘亏+免赔+其他免赔(酒水没有免赔)
                            BigDecimal zcjsLlhp = new BigDecimal(pkMap.get("zcjsPk"));
                            pkMap.put("zcjsLlhp", String.valueOf(zcjsLlhp));
                            //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                            BigDecimal zcjsSjhp = zcjsLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO : zcjsLlhp;
                            pkMap.put("zcjsSjhp", String.valueOf(Math.round(Double.valueOf(zcjsSjhp.doubleValue()))));
                        }
                    }
                }

                //新增盘亏表数据
                insertPankui(pkMap, cwHuopei.getShopCode(), cwHuopei.getBeginTime(), cwHuopei.getEndTime(), fiveM);
            }
        }
        pkMap.clear();//清空map

        //修改货赔表
        if (ToolUtil.isNotEmpty(hpList)){
            //每150条保存一次
            for(int i = 0; i < hpList.size();){
                int i2 = (i + 80);
                i2 = i2 > hpList.size() ? hpList.size() : i2;
                List<BtyCwHuopei> sub = hpList.subList(i, i2);
                //将这些数据改为通过状态
                baseMapper.updateList(sub);
                i = i2;
            }
        }
        return ResponseData.success();
    }

    //盘亏表新增数据
    public void insertPankui(Map<String,String> map, String shopCode, Date beginTime, Date endTime, String fiveM){
        List<BtyCwPankui> list = new ArrayList<>();

                //酒水盘亏 = 酒水 + 自采酒水 盘亏总计
                int jspk = Integer.valueOf(ToolUtil.isNotEmpty(map.get("jsPk")) ? map.get("jsPk") : "0") +
                        Integer.valueOf(ToolUtil.isNotEmpty(map.get("zcjsPk")) ? map.get("zcjsPk") : "0");

                //酒水理论货赔 盘亏+免赔+其他免赔(酒水没有免赔)
                int jsLl = jspk;
                //酒水实际货赔  -> 理论货赔金额大于0，取0; 小于0，取实际值
                int jsSj = jsLl > 0 ? 0 : jsLl;

                BtyCwPankui btyCwPankui = new BtyCwPankui();
                btyCwPankui.setShopCode(shopCode);
                btyCwPankui.setQjyPk(ToolUtil.isNotEmpty(map.get("qjyPk")) ? map.get("qjyPk") : "0");//清江鱼盘亏
                btyCwPankui.setJlPk(ToolUtil.isNotEmpty(map.get("jlPk")) ? map.get("jlPk") : "0");//酱料盘亏
                btyCwPankui.setJsPk(String.valueOf(jspk));//酒水盘亏
                btyCwPankui.setQjyMp(fiveM);//清江鱼免赔
                btyCwPankui.setJlMp(fiveM);//酱料免赔
                btyCwPankui.setJsMp("0");//酒水免赔
                btyCwPankui.setQjyOther("0");//清江鱼其他免赔
                btyCwPankui.setJlOther("0");//酱料其他免赔
                btyCwPankui.setJsOther("0");//酒水其他免赔
                btyCwPankui.setQjyLlhp(ToolUtil.isNotEmpty(map.get("qjyLlhp")) ? map.get("qjyLlhp") : "0");//清江鱼理论货赔
                btyCwPankui.setJlLlhp(ToolUtil.isNotEmpty(map.get("jlLlhp")) ? map.get("jlLlhp") : "0");//酱料理论货赔
                btyCwPankui.setJsLlhp(String.valueOf(jsLl));//酒水理论货赔
                btyCwPankui.setQjySjhp(ToolUtil.isNotEmpty(map.get("qjySjhp")) ? map.get("qjySjhp") : "0");//清江鱼实际货赔
                btyCwPankui.setJlSjhp(ToolUtil.isNotEmpty(map.get("jlSjhp")) ? map.get("jlSjhp") : "0");//酱料实际货赔
                btyCwPankui.setJsSjhp(String.valueOf(jsSj));//酒水实际货赔
                btyCwPankui.setQjyFine("0");//清江鱼罚款金额
                btyCwPankui.setJlFine("0");//酱料罚款金额
                btyCwPankui.setJsFine("0");//酒水罚款金额
                btyCwPankui.setBeginTime(beginTime);//开始时间
                btyCwPankui.setEndTime(endTime);//结束时间

                //货赔合计=罚款金额+实际货赔
                int heji = Integer.valueOf(ToolUtil.isNotEmpty(map.get("qjySjhp")) ? map.get("qjySjhp") : "0") +
                        Integer.valueOf(ToolUtil.isNotEmpty(map.get("jlSjhp")) ? map.get("jlSjhp") : "0") + jsSj;
                btyCwPankui.setHeji(String.valueOf(heji));//货赔合计

                list.add(btyCwPankui);

        //新增盘亏表
        if (ToolUtil.isNotEmpty(list)){
            //查询存在该月数据的盘亏店面
            List<BtyCwPankui> pkList = btyCwPankuiMapper.getPankuiByList(list, endTime);
            if (ToolUtil.isNotEmpty(pkList)){
                Map<String, BtyCwPankui> pkMap = pkList.stream().collect(Collectors.toMap(s -> s.getShopCode(), s ->s));
                Iterator<BtyCwPankui> iterator = list.iterator();
                while (iterator.hasNext()) {
                    BtyCwPankui pankui = iterator.next();
                    //如果盘亏表中存在该月该店数据，则新增list中删除此店
                    if (ToolUtil.isNotEmpty(pkMap.get(pankui.getShopCode()))) {
                        iterator.remove();
                    }
                }
//                //修改已经存在的数据
//                for (BtyCwPankui param : pkList) {
//                    btyCwPankuiMapper.update(param);
//                }
            }

            //每150条保存一次
            for(int i = 0; i < list.size();){
                int i2 = (i + 50);
                i2 = i2 > list.size() ? list.size() : i2;
                List<BtyCwPankui> sub = list.subList(i, i2);
                btyCwPankuiMapper.insertList(sub);
                i = i2;
            }
        }
    }

    /**
     * 获取城市列表
     * @return
     */
    @Override
    public ResponseData cityList() {
        //当前登陆者姓名
        String name = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        List<Map> list = new ArrayList<>();

        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
            list = this.baseMapper.cityList(null);
        }else if (roleNames.contains("会计")){
            //获取成本会计所对应城市
            list = this.baseMapper.cityList(name);
        }
        return ResponseData.success(list);
    }

    /**
     * 获取市列表
     * @param pid
     * @return
     */
    @Override
    public ResponseData cityNameList(Long pid) {
        //当前登陆者姓名
        String name = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        List<Map> list = new ArrayList<>();

        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
            list = this.baseMapper.cityNameList(null, pid);
        }else if (roleNames.contains("会计")){
            //获取成本会计所对应城市
            list = this.baseMapper.cityNameList(name, pid);
        }
        return ResponseData.success(list);
    }

    @Override
    public Boolean insertHp(List<BtyCwHpDto> list, List<String> codeList, String end, String begin) throws Exception {
        boolean notNull = false;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date beginTime = sdf.parse(begin);
        Date endTime = sdf.parse(end);

        //删除货赔表数据
        baseMapper.deleteList(codeList, endTime);
        //删除盘亏表数据
        btyCwPankuiMapper.deleteList(codeList, endTime);

        if(ToolUtil.isNotEmpty(list)){
            List<BtyCwHuopei> huopeiList = new ArrayList<>();
            for (BtyCwHpDto hpDto : list) {
                BtyCwHuopei cwHuopei = new BtyCwHuopei();
                cwHuopei.setNum(hpDto.getNum());
                cwHuopei.setShopCode(hpDto.getShopCode());
                cwHuopei.setShopName(hpDto.getShopName());
                cwHuopei.setClassName(hpDto.getClassName());
                cwHuopei.setProCode(hpDto.getProCode());
                cwHuopei.setProName(hpDto.getProName());
                cwHuopei.setSpec(hpDto.getSpec());
                cwHuopei.setUnit(hpDto.getUnit());
                cwHuopei.setPrice(hpDto.getPrice());
                cwHuopei.setAmountTotal(hpDto.getAmountTotal());
                cwHuopei.setThNum(hpDto.getThNum());
                cwHuopei.setRealNum(hpDto.getRealNum());
                cwHuopei.setNumTotal(hpDto.getNumTotal());
                cwHuopei.setCreateUser(LoginContextHolder.getContext().getUserId());
                cwHuopei.setCreateTime(new Date());
                cwHuopei.setBeginTime(beginTime);
                cwHuopei.setEndTime(endTime);

                huopeiList.add(cwHuopei);
            }

            notNull = baseMapper.insertHp(huopeiList);
        }
        return notNull;
    }

    /**
     * 发送门店
     * @param date
     * @param provinceId
     * @param cityId
     * @return
     */
    @Override
    public ResponseData sendMsg(String date, Long provinceId, Long cityId) {
        //当前登陆者姓名
        String name = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        List<String> dmList = new ArrayList<>();//当前登陆者所属店名
        List<String> list = new ArrayList<>();//要发消息的店名
        List<Map> dzList = new ArrayList<>();//获取店长信息

        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
            dmList = this.baseMapper.getDm(cityId,null, provinceId);
        }else if (roleNames.contains("成本会计")){
            dmList = this.baseMapper.getDm(cityId, name, provinceId);
        }

        if (ToolUtil.isNotEmpty(dmList)){
            list = this.baseMapper.getMsgList(date, dmList);

            if (ToolUtil.isNotEmpty(list)){
                dzList = bizShopMapper.getDzByBh(list);
            }
        }

        String time = date.split("-")[0] + "年" + date.split("-")[1] + "月";

//        Map<String, String> map = new HashMap<>();
//        map.put("name", "111");
//        map.put("code", "666");
//        map.put("shopowner","'17864739382'");
//        map.put("yaoma", "999");
//        pushMsgService.huopeiToIM(map, time);

        //推送店长消息
        if (ToolUtil.isNotEmpty(dzList)){
            for (Map map : dzList) {
                pushMsgService.huopeiToIM(map, time);
            }

            //修改状态为已推送门店
            baseMapper.updateSta(date, list);
        }

        return ResponseData.success();
    }

    /**
     * 获取供应链货赔详情
     * @param storeIdList
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public ResponseData scmDetail(List<String> storeIdList, String startTime, String endTime) {
        // 请求地址（测试）
//        String url = "http://355ae29341.wicp.vip/reptInvApi/queryList";
//        String url = "http://supply.metacatering.cn/api/chain/reptInvApi/queryList";
        //请求地址（正式）
        String url = "https://supply.imugua.tech/api/chain/reptInvApi/queryList";

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date begin = sdf.parse(startTime);//开始日期
            Date end = sdf.parse(endTime);//结束日期

            // 获取http客户端
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost postMethod = new HttpPost(url);
            // 自定义对象
            Map<String,Object> map = new HashMap<>();
            map.put("COMPANY_ID", LogUtil.tokenGetter().get("companyId"));
            map.put("SHOP_ID", LogUtil.tokenGetter().get("SHOP_ID"));
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            if (ToolUtil.isNotEmpty(storeIdList)){
                map.put("storeIdList", storeIdList);
            }
            // 设置请求头
            postMethod.addHeader("Content-Type", "application/json;charset=utf8");
            postMethod.setHeader("token",LogUtil.tokenGetter().get("token"));


                // 封装请求体
                postMethod.setEntity(new StringEntity(JSON.toJSONString(map), Charset.forName("UTF-8")));
                // 发送请求(post请求)
                HttpResponse response = httpClient.execute(postMethod);
                // 获取响应结果
                int statusCode = response.getStatusLine().getStatusCode();
                // 响应对象
                HttpEntity httpEntity = response.getEntity();
                // 响应的字符串
                String responseContent = EntityUtils.toString(httpEntity, "UTF-8");
                //转化为JSON格式
                JSONObject jsonObject = JSONObject.parseObject(responseContent);


                if (jsonObject.get("status").equals("ok")){
                    String data = jsonObject.getString("data");
                    logger.info("----------" + data);

                    //将json格式的数据转换成list
                    List<ScmHuopeiDto> list = JSON.parseArray(data, ScmHuopeiDto.class);
                    //新增数据到数据库中
                    addScmHuopei(list, begin, end);
                    EntityUtils.consume(httpEntity);
                    return ResponseData.success();

                }else {
                    logger.error("请求失败，" + jsonObject.get("msg"));
                    return ResponseData.error("请求失败，" + jsonObject.get("msg"));
                }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public ResponseData addScmHuopei(List<ScmHuopeiDto> list, Date begin, Date end){
        BtyCwHuopei btyCwHuopei = new BtyCwHuopei();
        List<String> codeList = new ArrayList<>();
        List<BtyCwHuopei> huopeiList = new ArrayList<>();
        List<Map<String,String>> nameList = nameRelationService.getName();
        Map<String, Map<String,String>> nameMap = nameList.stream().collect(Collectors.toMap(s -> s.get("scmCode"), s -> s));


        //将数据循环添加到list集合中
        for (ScmHuopeiDto scmHuopei : list) {
            String className = scmHuopei.getDishType();//品项类别名称
            String scmCode = scmHuopei.getStoreLmnid();//木瓜门店编号(长号)
//            String scmCode = scmHuopei.getStoreId();//木瓜门店编号(长号)
            String shopCode = "";
            Map<String, String> map = nameMap.get(scmCode);
            if (ToolUtil.isNotEmpty(map)){
                shopCode = map.get("shopCode");
            }

            //shopCode不为空，只取冻货、酱料、酒水、自采酒水
            if (ToolUtil.isNotEmpty(shopCode) && ToolUtil.isNotEmpty(className) && (className.contains("冻货") || className.contains("酱料") || className.contains("酒水"))){
                btyCwHuopei.setShopCode(shopCode);//门店编号
                btyCwHuopei.setShopName(scmHuopei.getStore());//门店名称 store
                btyCwHuopei.setClassName(className);//品项类别名称 dishtype
                btyCwHuopei.setProCode(scmHuopei.getDishItemNumber());//品项编号 dishitemnumber
                btyCwHuopei.setProName(scmHuopei.getDish());//品项名称 dish
                btyCwHuopei.setSpec(scmHuopei.getDishStandard());//规格 dishstandard
                btyCwHuopei.setUnit(scmHuopei.getDishUnit());//单位 dishunit
                btyCwHuopei.setThNum(scmHuopei.getTheoryQuantity());//理论耗用数量 theoryquantity
                btyCwHuopei.setRealNum(scmHuopei.getActualQuantity());//实际耗用数量 actualquantity

                String poorConsumption = scmHuopei.getPoorConsumption();
                BigDecimal bigDecimal = new BigDecimal(poorConsumption);
                btyCwHuopei.setNumTotal(bigDecimal.toPlainString());//耗用数量分差 poorconsumption

                btyCwHuopei.setScmClassCode(scmHuopei.getDishTypeCode());//木瓜品项类别编号 dishtypecode
                btyCwHuopei.setScmCode(scmCode);//木瓜门店编号 storeLmnid

                String poorConsumptionAmount = scmHuopei.getPoorConsumptionAmount();
                BigDecimal amountDecimal = new BigDecimal(poorConsumptionAmount);
                btyCwHuopei.setScmAmount(amountDecimal.toPlainString());//木瓜耗用金额分差 poorconsumptionamount

                btyCwHuopei.setScmPrice(scmHuopei.getStockPrice());//木瓜单价 stockprice
                btyCwHuopei.setBeginTime(begin);//开始时间
                btyCwHuopei.setEndTime(end);//结束时间
                btyCwHuopei.setScmStatus(0);//0->供应链获取，1->数据导入
                btyCwHuopei.setCreateTime(new Date());
                btyCwHuopei.setCreateUser(LoginContextHolder.getContext().getUserId());
                btyCwHuopei.setAmountTotal("0");//耗用金额分差
                btyCwHuopei.setPrice("0");//非税成本单价

                huopeiList.add(btyCwHuopei);
                codeList.add(btyCwHuopei.getShopCode());

                btyCwHuopei = new BtyCwHuopei();
            }
        }
        //删除相关数据
        for(int i = 0; i < codeList.size();){
            int i2 = (i + 300);
            i2 = i2 > codeList.size() ? codeList.size() : i2;
            List<String> sub = codeList.subList(i, i2);
            //删除货赔表数据
            baseMapper.deleteList(sub, end);
            //删除盘亏表数据
            btyCwPankuiMapper.deleteList(sub, end);
            i = i2;
        }
        //新增货赔表数据
        //每150条保存一次
        for(int i = 0; i < huopeiList.size();){
            int i2 = (i + 80);
            i2 = i2 > huopeiList.size() ? huopeiList.size() : i2;
            List<BtyCwHuopei> sub = huopeiList.subList(i, i2);
            baseMapper.insertHp(sub);
            i = i2;
        }
        return ResponseData.success();
    }


//    public ResponseData scmDetail(List<String> storeIdList, String startTime, String endTime) {
//        // 请求地址
////        String url = "http://355ae29341.wicp.vip/reptinventory/queryList";
//        String url = "http://supply.metacatering.cn/api/chain/reptinventory/queryList";
//
//        try {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            Date begin = sdf.parse(startTime);//开始日期
//            Date end = sdf.parse(endTime);//结束日期
//
//            // 获取http客户端
//            HttpClient httpClient = HttpClients.createDefault();
//            HttpPost postMethod = new HttpPost(url);
//            // 自定义对象
//            Map<String,Object> map = new HashMap<>();
//            map.put("COMPANY_ID", LogUtil.tokenGetter().get("companyId"));
//            map.put("SHOP_ID", LogUtil.tokenGetter().get("SHOP_ID"));
//            map.put("startTime", startTime);
//            map.put("endTime", endTime);
//            if (ToolUtil.isNotEmpty(storeIdList)){
//                map.put("storeIdList", storeIdList);
//            }
//            int current = 1;
//            int pageSize = 1000;
//            // 设置请求头
//            postMethod.addHeader("Content-Type", "application/json;charset=utf8");
//            postMethod.setHeader("token",LogUtil.tokenGetter().get("token"));
//
//            List<String> list1 = new ArrayList<>();
//            while (true){
//                map.put("current", current);
//                map.put("pageSize", pageSize);
//
//                // 封装请求体
//                postMethod.setEntity(new StringEntity(JSON.toJSONString(map), Charset.forName("UTF-8")));
//                // 发送请求(post请求)
//                HttpResponse response = httpClient.execute(postMethod);
//                // 获取响应结果
//                int statusCode = response.getStatusLine().getStatusCode();
//                // 响应对象
//                HttpEntity httpEntity = response.getEntity();
//                // 响应的字符串
//                String responseContent = EntityUtils.toString(httpEntity, "UTF-8");
//                //转化为JSON格式
//                JSONObject jsonObject = JSONObject.parseObject(responseContent);
//
//
//                if (jsonObject.get("status").equals("ok")){
//                    String data = jsonObject.getString("data");
//                    logger.info("----------" + data);
//
//                    //将json格式的数据转换成list
//                    List<String> list = JSON.parseArray(data,String.class);
//
//                    list1.addAll(list);
//
//                    Integer total = list.size();
//                    if (total < pageSize){
//                        break;
//                    }
//                    current++;
//                }else {
//                    logger.error("请求失败，" + jsonObject.get("msg"));
//                    return ResponseData.error("请求失败，" + jsonObject.get("msg"));
//                }
//
//                EntityUtils.consume(httpEntity);
//            }
//
//            //新增数据到数据库中
//            addScmHuopei(list1, begin, end);
//            return ResponseData.success(list1);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }

    /**
     * 将同步的货赔数据新增到数据库中
     * @return
     */
//    public ResponseData addScmHuopei(List<String> list, Date begin, Date end){
//        BtyCwHuopei btyCwHuopei = new BtyCwHuopei();
//        List<String> codeList = new ArrayList<>();
//        List<BtyCwHuopei> huopeiList = new ArrayList<>();
//        List<Map<String,String>> nameList = nameRelationService.getName();
//        Map<String, Map<String,String>> nameMap = nameList.stream().collect(Collectors.toMap(s -> s.get("scmCode"), s -> s));
//
//
//        //将数据循环添加到list集合中
//        for (int i = 0; i < list.size() ; i++) {
//            String[] split = list.get(i).split(",");
//            String className = split[21].replace("\"", "").equals("null") ? "" : split[21].replace("\"", "");
//            String scmCode = split[17].replace("\"", "").equals("null") ? "" : split[17].replace("\"", "");
//            String shopCode = "";
//            Map<String, String> map = nameMap.get(scmCode);
//            if (ToolUtil.isNotEmpty(map)){
//                shopCode = map.get("shopCode");
//            }
//
//            //只取冻货、酱料、酒水、自采酒水
//            if (!"null".equals(split[14].replace("\"", "")) && (className.contains("冻货") || className.contains("酱料") || className.contains("酒水"))){
//                btyCwHuopei.setShopCode(shopCode);//门店编号
//                btyCwHuopei.setShopName(split[15].replace("\"", "").equals("null") ? "" : split[15].replace("\"", ""));//门店名称 store
//                btyCwHuopei.setClassName(className);//品项类别名称 dishtype
//                btyCwHuopei.setProCode(split[6].replace("\"", "").equals("null") ? "" : split[6].replace("\"", ""));//品项编号 dishitemnumber
//                btyCwHuopei.setProName(split[20].replace("\"", "").equals("null") ? "" : split[20].replace("\"", ""));//品项名称 dish
//                btyCwHuopei.setSpec(split[13].replace("\"", "").equals("null") ? "" : split[13].replace("\"", ""));//规格 dishstandard
//                btyCwHuopei.setUnit(split[24].replace("\"", "").equals("null") ? "" : split[24].replace("\"", ""));//单位 dishunit
//                btyCwHuopei.setThNum(split[10].replace("\"", "").equals("null") ? "0" : split[10].replace("\"", ""));//理论耗用数量 theoryquantity
//                btyCwHuopei.setRealNum(split[7].replace("\"", "").equals("null") ? "0" : split[7].replace("\"", ""));//实际耗用数量 actualquantity
//                btyCwHuopei.setNumTotal(split[22].replace("\"", "").equals("null") ? "0" : split[22].replace("\"", ""));//耗用数量分差 poorconsumption
//                btyCwHuopei.setScmClassCode(split[25].replace("\"", "").replace("]", "").equals("null") ? "" : split[25].replace("\"", "").replace("]", ""));//木瓜品项类别编号 dishtypecode
//                btyCwHuopei.setScmCode(split[17].replace("\"", "").equals("null") ? "" : split[17].replace("\"", ""));//木瓜门店编号 storeid
//                btyCwHuopei.setScmAmount(split[23].replace("\"", "").equals("null") ? "" : split[23].replace("\"", ""));//木瓜耗用金额分差 poorconsumptionamount
//                btyCwHuopei.setScmPrice(split[4].replace("\"", "").equals("null") ? "" : split[4].replace("\"", ""));//木瓜单价 stockprice
//                btyCwHuopei.setBeginTime(begin);//开始时间
//                btyCwHuopei.setEndTime(end);//结束时间
//                btyCwHuopei.setScmStatus(0);//0->供应链获取，1->数据导入
//                btyCwHuopei.setCreateTime(new Date());
//                btyCwHuopei.setCreateUser(LoginContextHolder.getContext().getUserId());
//                btyCwHuopei.setAmountTotal("0");//耗用金额分差
//                btyCwHuopei.setPrice("0");//非税成本单价
//
//                huopeiList.add(btyCwHuopei);
//                codeList.add(btyCwHuopei.getShopCode());
//
//                btyCwHuopei = new BtyCwHuopei();
//            }
//        }
//        //删除相关数据
//        for(int i = 0; i < codeList.size();){
//            int i2 = (i + 300);
//            i2 = i2 > codeList.size() ? codeList.size() : i2;
//            List<String> sub = codeList.subList(i, i2);
//            //删除货赔表数据
//            baseMapper.deleteList(sub, end);
//            //删除盘亏表数据
//            btyCwPankuiMapper.deleteList(sub, end);
//            i = i2;
//        }
//        //新增货赔表数据
//        //每150条保存一次
//        for(int i = 0; i < huopeiList.size();){
//            int i2 = (i + 80);
//            i2 = i2 > huopeiList.size() ? huopeiList.size() : i2;
//            List<BtyCwHuopei> sub = huopeiList.subList(i, i2);
//            baseMapper.insertHp(sub);
//            i = i2;
//        }
//        return ResponseData.success();
//    }

    /**
     * 同步单店货赔价格
     * @param date
     * @param shopCode
     * @return
     */
    @Override
    public ResponseData editDdhp(String date, String shopCode) {
        //获取货赔单价
        List<Map> list = cwJsMapper.getHpList(date);
        List<BtyCwHuopei> jsList = new ArrayList<>();
        List<BtyCwHuopei> jlList = new ArrayList<>();
        //修改货赔表货赔单价
        if(ToolUtil.isNotEmpty(list)){
            for (Map map : list) {

                //品相编号不为空 -> 酒水
                if (ToolUtil.isNotEmpty(map.get("pro_code"))){
                    BtyCwHuopei cwHuopei = new BtyCwHuopei();
                    cwHuopei.setPrice(map.get("price").toString());//酒水价格
                    cwHuopei.setProCode(map.get("pro_code").toString());//品项编号
                    cwHuopei.setShopCode(shopCode);//门店编号

                    jsList.add(cwHuopei);

                    //木瓜品项类别编号不为空 -> 酱料，冻货
                }else if (ToolUtil.isNotEmpty(map.get("scm_class_code"))){

                    String className = "";
                    BtyCwHuopei cwHuopei = new BtyCwHuopei();
                    cwHuopei.setPrice(map.get("price").toString());//酱料，冻货价格
                    if (map.get("class_name").equals("2")){
                        className = "酱料";
                    }else if (map.get("class_name").equals("3")){
                        className = "冻货";
                    }
                    cwHuopei.setClassName(className);
                    cwHuopei.setScmClassCode(map.get("scm_class_code").toString());//品项类别编号
                    cwHuopei.setShopCode(shopCode);//门店编号

                    jlList.add(cwHuopei);
                }

            }

            List<BtyCwHuopei> hpList = new ArrayList<>();//获取修改卖价的主键ID
            //修改货赔表酒水单价
            if (ToolUtil.isNotEmpty(jsList)){
                baseMapper.editJsPriceList(jsList, date);
                //获取修改卖价的主键ID
                List<BtyCwHuopei> jshpList = baseMapper.getJsList(jsList, date, shopCode);
                hpList.addAll(jshpList);
            }
            //修改货赔表酱料，冻货单价
            if (ToolUtil.isNotEmpty(jlList)){
                baseMapper.editHpPriceList(jlList, date);
                //获取修改卖价的主键ID
                List<BtyCwHuopei> dhhpList = baseMapper.getHpList(jlList, date, shopCode);
                hpList.addAll(dhhpList);
            }

            if (ToolUtil.isNotEmpty(hpList)){
                for (BtyCwHuopei huopei : hpList) {
                    BigDecimal price = new BigDecimal(huopei.getPrice());
                    BigDecimal num = new BigDecimal(huopei.getNumTotal());

                    //耗用金额分差 = 非税成本单价 * 耗用数量分差
                    BigDecimal amountTotal = price.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
                    huopei.setAmountTotal(amountTotal.toString());
                }
                baseMapper.editAmount(hpList);//修改耗用金额分差
            }

            editHpPankui(hpList);//计算盘亏数据
        }

        return ResponseData.success();
    }

    /**
     * 计算货赔盘亏数据
     * @param list
     * @return
     */
    @Override
    @Async
    public ResponseData editHpPankui(List<BtyCwHuopei> list){
//        //门店编码list不为空（批量同步货赔单价）
//        if (ToolUtil.isNotEmpty(shopList)){
//            //获取盘亏数据
//            List<BtyCwPankui> pankuiList = btyCwPankuiMapper.getPankuiList(shopList, list.get(0).getEndTime());
//            //获取货赔表酱料耗用金额分差小计
//            List<BtyCwHuopei> jlAmountList = baseMapper.jlAmountList(shopList, list.get(0).getEndTime());
//            Map<String, String> jlAmountMap = jlAmountList.stream().collect(Collectors.toMap(s -> s.getShopCode(), s -> s.getAmountTotal()));
//
//            //获取货赔表冻货耗用金额分差小计
//            List<BtyCwHuopei> dhAmountList = baseMapper.dhAmountList(shopList, list.get(0).getEndTime());
//            Map<String, String> dhAmountMap = dhAmountList.stream().collect(Collectors.toMap(s -> s.getShopCode(), s -> s.getAmountTotal()));
//
//
//            if (ToolUtil.isNotEmpty(pankuiList)){
//                for (BtyCwPankui pankui : pankuiList) {
//                    if (ToolUtil.isNotEmpty(jlAmountMap.get(pankui.getShopCode()))){
//
//                    }
//                }
//            }
//
//        }
        if (ToolUtil.isNotEmpty(list)){
            List<BtyCwPankui> pankuiList = new ArrayList<>();
            for(int i = 0; i < list.size();){
                int i2 = (i + 1900);
                i2 = i2 > list.size() ? list.size() : i2;
                List<BtyCwHuopei> sub = list.subList(i, i2);
                List<BtyCwPankui> lists = btyCwPankuiMapper.getPankuiList(sub, list.get(0).getEndTime());

//                //获取货赔表酱料耗用金额分差小计
//                List<BtyCwHuopei> jlAmountList = baseMapper.jlAmountList(sub, list.get(0).getEndTime());
//                Map<String, String> jlAmountMap = jlAmountList.stream().collect(Collectors.toMap(s -> s.getShopCode(), s -> s.getAmountTotal()));
//
//                //获取货赔表冻货耗用金额分差小计
//                List<BtyCwHuopei> dhAmountList = baseMapper.dhAmountList(sub, list.get(0).getEndTime());
//                Map<String, String> dhAmountMap = dhAmountList.stream().collect(Collectors.toMap(s -> s.getShopCode(), s -> s.getAmountTotal()));
//
//                //获取货赔表酒水耗用金额分差小计
//                List<BtyCwHuopei> jsAmountList = baseMapper.jsAmountList(sub, list.get(0).getEndTime());
//                Map<String, String> jsAmountMap = jsAmountList.stream().collect(Collectors.toMap(s -> s.getShopCode(), s -> s.getAmountTotal()));
//
//                //获取货赔表自采酒水耗用金额分差小计
//                List<BtyCwHuopei> zcjsAmountList = baseMapper.zcjsAmountList(sub, list.get(0).getEndTime());
//                Map<String, String> zcjsAmountMap = zcjsAmountList.stream().collect(Collectors.toMap(s -> s.getShopCode(), s -> s.getAmountTotal()));


                i = i2;
                pankuiList.addAll(lists);
            }
            pankuiList = pankuiList.stream()
                    // 去重
                    .filter(distinctByName(BtyCwPankui::getShopCode))
                    .collect(Collectors.toList());

            Map<String, BtyCwPankui> pankuiMap = pankuiList.stream().collect(Collectors.toMap(s -> s.getShopCode(), s -> s));

            //获取货赔表酱料耗用金额分差小计
            List<BtyCwHuopei> jlAmountList = baseMapper.jlAmountList(null, list.get(0).getEndTime());
            Map<String, BtyCwHuopei> jlAmountMap = jlAmountList.stream().collect(Collectors.toMap(s -> s.getShopCode(), s -> s));

            //获取货赔表冻货耗用金额分差小计
            List<BtyCwHuopei> dhAmountList = baseMapper.dhAmountList(null, list.get(0).getEndTime());
            Map<String, BtyCwHuopei> dhAmountMap = dhAmountList.stream().collect(Collectors.toMap(s -> s.getShopCode(), s -> s));

            //获取货赔表酒水耗用金额分差小计
            List<BtyCwHuopei> jsAmountList = baseMapper.jsAmountList(null, list.get(0).getEndTime());
            Map<String, BtyCwHuopei> jsAmountMap = jsAmountList.stream().collect(Collectors.toMap(s -> s.getShopCode(), s -> s));

            //获取货赔表自采酒水耗用金额分差小计
            List<BtyCwHuopei> zcjsAmountList = baseMapper.zcjsAmountList(null, list.get(0).getEndTime());
            Map<String, BtyCwHuopei> zcjsAmountMap = zcjsAmountList.stream().collect(Collectors.toMap(s -> s.getShopCode(), s -> s));


            //获取该店的盘亏数据
//            BtyCwPankui pankui = btyCwPankuiMapper.getPankui(list.get(0).getShopCode(), list.get(0).getEndTime());
//            //获取货赔表该店酱料耗用金额分差小计
//            BigDecimal jlAmount = baseMapper.jlAmount(list.get(0));
//            if (ToolUtil.isEmpty(jlAmount)){
//                jlAmount = BigDecimal.ZERO;
//            }
//
//            //获取货赔表该店冻货耗用金额分差小计
//            BigDecimal dhAmount = baseMapper.dhAmount(list.get(0));
//            if (ToolUtil.isEmpty(dhAmount)){
//                dhAmount = BigDecimal.ZERO;
//            }

            List<BtyCwPankui> pankuis = new ArrayList<>();
            for (BtyCwHuopei huopei : list) {
                BtyCwPankui pankui = pankuiMap.get(huopei.getShopCode());
                BtyCwHuopei jl = jlAmountMap.get(huopei.getShopCode());
                BtyCwHuopei dh = dhAmountMap.get(huopei.getShopCode());
                BtyCwHuopei js = jsAmountMap.get(huopei.getShopCode());
                BtyCwHuopei zcjs = zcjsAmountMap.get(huopei.getShopCode());

                //获取货赔表该店酱料耗用金额分差小计
//                BigDecimal jlAmount = baseMapper.jlAmount(huopei);
                BigDecimal jlAmount = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(jl) && ToolUtil.isNotEmpty(jl.getAmountTotal())){
                    jlAmount = new BigDecimal(jl.getAmountTotal());
                }

                //获取货赔表该店冻货耗用金额分差小计
//                BigDecimal dhAmount = baseMapper.dhAmount(huopei);
                BigDecimal dhAmount = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(dh) && ToolUtil.isNotEmpty(dh.getAmountTotal())){
                    dhAmount = new BigDecimal(dh.getAmountTotal());
                }

                //获取货赔表该店酒水数据(负数合计)
//                BigDecimal jsAmount = baseMapper.jsAmount(huopei);
                BigDecimal jsAmount = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(js) && ToolUtil.isNotEmpty(js.getAmountTotal())){
                    jsAmount = new BigDecimal(js.getAmountTotal());
                }

                //获取货赔表该店自采酒水数据(负数合计)
//                BigDecimal zcjsAmount = baseMapper.zcjsAmount(huopei);
                BigDecimal zcjsAmount = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(zcjs) && ToolUtil.isNotEmpty(zcjs.getAmountTotal())){
                    zcjsAmount = new BigDecimal(zcjs.getAmountTotal());
                }
//                BigDecimal zcjsAmount = new BigDecimal(zcjs.getAmountTotal());


//                if (huopei.getClassName().equals("酒水")){
//
//                    //此酒水的耗用金额分差
//                    BigDecimal jsPr = new BigDecimal(huopei.getNumTotal()).multiply(new BigDecimal(huopei.getPrice()));
//                    jsPr = jsPr.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO : jsPr;
//
//                    //酒水耗用金额分差小计（除此酒水外酒水耗用金额分差之和 + 此酒水的耗用金额分差）
//                    jsAmount = jsAmount.add(jsPr);
//                }
//                if (huopei.getClassName().equals("自采酒水")){
//
//                    //此酒水的耗用金额分差
//                    BigDecimal zcjsPr = new BigDecimal(huopei.getNumTotal()).multiply(new BigDecimal(huopei.getPrice()));
//                    zcjsPr = zcjsPr.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO : zcjsPr;
//
//                    //自采酒水耗用金额分差小计
//                    zcjsAmount = zcjsAmount.add(zcjsPr);
//                }
                huopei.setJlAmSum(jlAmount.toString());//酱料耗用金额分差小计
                huopei.setDhAmSum(dhAmount.toString());//冻货耗用金额分差小计
                huopei.setJsAmSum(jsAmount.toString());
                huopei.setZcjsAmSum(zcjsAmount.toString());

//                baseMapper.updateXj(huopei);//修改货赔表数据

                if (ToolUtil.isNotEmpty(pankui)){

                    //酒水盘亏 = 酒水耗用金额分差小计 + 自采酒水耗用金额分差小计
                    BigDecimal jsPk = jsAmount.add(zcjsAmount).setScale(0, BigDecimal.ROUND_HALF_UP);
                    pankui.setJsPk(jsPk.toString());

                    //酱料盘亏 = 酱料耗用金额分差小计
                    BigDecimal jlPk = jlAmount.setScale(0, BigDecimal.ROUND_HALF_UP);
                    jlPk = jlPk.compareTo(BigDecimal.ZERO) >= 0 ? BigDecimal.ZERO : jlPk;
                    pankui.setJlPk(jlPk.toString());

                    //冻货盘亏 = 冻货耗用金额分差小计
                    BigDecimal dhPk = dhAmount.setScale(0, BigDecimal.ROUND_HALF_UP);
                    dhPk = dhPk.compareTo(BigDecimal.ZERO) >= 0 ? BigDecimal.ZERO : dhPk;
                    pankui.setQjyPk(dhPk.toString());

                    //计算酒水理论货赔（等于盘亏+免赔+其他免赔）
                    BigDecimal jsLlhp = jsPk.add(new BigDecimal(pankui.getJsMp())).add(new BigDecimal(pankui.getJsOther())).setScale(0, BigDecimal.ROUND_HALF_UP);
                    pankui.setJsLlhp(jsLlhp.toString());

                    //计算酱料理论货赔（等于盘亏+免赔+其他免赔）
                    BigDecimal jlLlhp = jlPk.add(new BigDecimal(pankui.getJlMp())).add(new BigDecimal(pankui.getJlOther())).setScale(0, BigDecimal.ROUND_HALF_UP);
                    pankui.setJlLlhp(jlLlhp.toString());

                    //计算冻货理论货赔（等于盘亏+免赔+其他免赔）
                    BigDecimal dhLlhp = dhPk.add(new BigDecimal(pankui.getQjyMp())).add(new BigDecimal(pankui.getQjyOther())).setScale(0, BigDecimal.ROUND_HALF_UP);
                    pankui.setQjyLlhp(dhLlhp.toString());

                    //计算酒水实际货赔（如果理论货赔金额大于0，取0；小于0，取实际值）
                    BigDecimal jsSjhp = jsLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jsLlhp;
                    pankui.setJsSjhp(jsSjhp.toString());

                    //计算酱料实际货赔（如果理论货赔金额大于0，取0；小于0，取实际值）
                    BigDecimal jlSjhp = jlLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jlLlhp;
                    pankui.setJlSjhp(jlSjhp.toString());

                    //计算冻货实际货赔（如果理论货赔金额大于0，取0；小于0，取实际值）
                    BigDecimal dhSjhp = dhLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :dhLlhp;
                    pankui.setQjySjhp(dhSjhp.toString());

                    //计算货赔合计（货赔合计=罚款金额+实际货赔）
                    BigDecimal hphj = new BigDecimal(pankui.getQjyFine()).add(new BigDecimal(pankui.getQjySjhp()))
                            .add(new BigDecimal(pankui.getJlFine())).add(new BigDecimal(pankui.getJlSjhp()))
                            .add(new BigDecimal(pankui.getJsFine())).add(jsSjhp);
                    hphj.setScale(0, BigDecimal.ROUND_HALF_UP);
                    pankui.setHeji(hphj.toString());
                    pankuis.add(pankui);
//                    btyCwPankuiMapper.update(pankui);//修改盘亏表数据
                }

            }

            if (ToolUtil.isNotEmpty(pankuis)){
                //根据code去重
                pankuis = pankuis.stream()
                        // 去重
                        .filter(distinctByName(BtyCwPankui::getShopCode))
                        .collect(Collectors.toList());

                for(int i = 0; i < pankuis.size();){
                    int i2 = (i + 80);
                    i2 = i2 > pankuis.size() ? pankuis.size() : i2;
                    List<BtyCwPankui> sub = pankuis.subList(i, i2);
                    btyCwPankuiMapper.updateList(sub);
                    i = i2;
                }
            }

            //根据code去重
            list = list.stream()
                    // 去重
                    .filter(distinctByName(BtyCwHuopei::getShopCode))
                    .collect(Collectors.toList());

            for(int i = 0; i < list.size();){
                int i2 = (i + 300);
                i2 = i2 > list.size() ? list.size() : i2;
                List<BtyCwHuopei> sub = list.subList(i, i2);
                baseMapper.updateXjList(sub);
                i = i2;
            }
//            baseMapper.updateXj(list);//修改货赔表数据


        }

        return ResponseData.success();
    }


    public static <T> Predicate<T> distinctByName(Function<? super T, ?> keyExtractor) {
        //该方法返回一个具有哈希映射键的集合。
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }


    /**
     * 同步货赔单价(批量)
     * @param date
     * @return
     */
    @Override
    public ResponseData editPrice(String date) {
        //获取货赔单价
        List<Map> list = cwJsMapper.getHpList(date);
        List<BtyCwHuopei> jsList = new ArrayList<>();
        List<BtyCwHuopei> jlList = new ArrayList<>();

        //修改货赔表货赔单价
        if(ToolUtil.isNotEmpty(list)){
            for (Map map : list) {
                //品相编号不为空 -> 酒水
                if (ToolUtil.isNotEmpty(map.get("pro_code"))){
                    BtyCwHuopei cwHuopei = new BtyCwHuopei();
                    cwHuopei.setPrice(map.get("price").toString());//酒水价格
                    cwHuopei.setProCode(map.get("pro_code").toString());//品项编号
                    jsList.add(cwHuopei);

                    //木瓜品项类别编号不为空 -> 酱料，冻货
                }else if (ToolUtil.isNotEmpty(map.get("scm_class_code"))){

                    String className = "";
                    BtyCwHuopei cwHuopei = new BtyCwHuopei();
                    cwHuopei.setPrice(map.get("price").toString());//酱料，冻货价格
                    if (map.get("class_name").equals("2")){
                        className = "酱料";
                    }else if (map.get("class_name").equals("3")){
                        className = "冻货";
                    }
                    cwHuopei.setClassName(className);
                    cwHuopei.setScmClassCode(map.get("scm_class_code").toString());//品项类别编号

                    jlList.add(cwHuopei);
                }

            }

            List<BtyCwHuopei> hpList = new ArrayList<>();//获取修改卖价的主键ID
//            List<String> shopList = new ArrayList<>();//获取修改卖价的shop_code

            //修改货赔表酒水单价
            if (ToolUtil.isNotEmpty(jsList)){

                for(int i = 0; i < jsList.size();){
                    int i2 = (i + 200);
                    i2 = i2 > jsList.size() ? jsList.size() : i2;
                    List<BtyCwHuopei> sub = jsList.subList(i, i2);
                    baseMapper.editJsList(sub, date);
                    i = i2;
                }

                //获取修改卖价的主键ID
                List<BtyCwHuopei> jshpList = baseMapper.getJsLists(jsList, date);
                hpList.addAll(jshpList);
//                List<String> jsShopList = baseMapper.getJsCodes(jsList, date);
//                shopList.addAll(jsShopList);
            }

            //修改货赔表酱料，冻货单价
            if (ToolUtil.isNotEmpty(jlList)){

                for(int i = 0; i < jlList.size();){
                    int i2 = (i + 200);
                    i2 = i2 > jlList.size() ? jlList.size() : i2;
                    List<BtyCwHuopei> sub = jlList.subList(i, i2);
                    baseMapper.editHpList(sub, date);
                    i = i2;
                }

                //获取修改卖价的主键ID
                List<BtyCwHuopei> dhhpList = baseMapper.getHpLists(jlList, date);
                hpList.addAll(dhhpList);

//                List<String> dhShopList = baseMapper.getDhCodes(jlList, date);
//                shopList.removeAll(dhShopList);
//                shopList.addAll(dhShopList);
            }

            if (ToolUtil.isNotEmpty(hpList)){
                for (BtyCwHuopei huopei : hpList) {
                    BigDecimal price = new BigDecimal(huopei.getPrice());
                    BigDecimal num = new BigDecimal(huopei.getNumTotal());

                    //耗用金额分差 = 非税成本单价 * 耗用数量分差
                    BigDecimal amountTotal = price.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
                    huopei.setAmountTotal(amountTotal.toString());
                }

                //每500条保存一次
                for(int i = 0; i < hpList.size();){
                    int i2 = (i + 1900);
                    i2 = i2 > hpList.size() ? hpList.size() : i2;
                    List<BtyCwHuopei> sub = hpList.subList(i, i2);
                    //修改耗用金额分差
                    baseMapper.editAmount(sub);
                    i = i2;
                }
            }

            editHpPankui(hpList);//计算盘亏数据

        }

        return ResponseData.success();
    }

    /**
     * 批量导出excel
     * @param request
     * @param response
     * @param date
     * @return
     */
    @Override
    public ResponseEntity<byte[]> exportBatch(HttpServletRequest request, HttpServletResponse response, String date) {

        try {
            //TODO-1 要导出的数据内容

            //获取所有时间段
            List<BtyCwHuopei> timeList = baseMapper.selectTime(new BtyCwHuopei(), date);

            //要导出的list
            List<BtyCwHuopei> list = new ArrayList<>();
            //获取数据库有营业额的店
            List<BtyCwHuopei> turnList = baseMapper.getTurnList(date);
            if (ToolUtil.isNotEmpty(turnList)){
                //有数据 直接获取列表
                list = exportHuopeiList(turnList,date);
            }

            //获取数据库没有营业额的店
//            List<BtyCwHuopei> noTurnList = baseMapper.getNoTurnList(date);
//            //计算
//            if (ToolUtil.isNotEmpty(noTurnList)){
//                list = getHuopeiList(noTurnList, date);
//            }

            BaseFrontController baseFrontController = new BaseFrontController();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            if (timeList.size() > 1){
                //文件名称
                String begin = sdf.format(timeList.get(0).getBeginTime());
                String begin1 = sdf.format(timeList.get(timeList.size()-1).getBeginTime());
                String time = begin.split("-")[1];
                String time1 = begin1.split("-")[1];
                String name = time + "月-" + time1 + "月货赔表";

                return baseFrontController.buildResponseEntity(expBatch(list, timeList), name + ".xls");

            }else if (timeList.size() == 1){
                //文件名称
                String begin = sdf.format(list.get(0).getBeginTime());
                String time = begin.split("-")[1];
                String name = time + "月货赔表";
                return baseFrontController.buildResponseEntity(expBatch(list, timeList), name + ".xls");

            } else {
                return baseFrontController.buildResponseEntity(null, null + ".xls");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 有数据 直接获取列表
     * @param list
     * @param date
     * @return
     */
    private List<BtyCwHuopei> exportHuopeiList(List<BtyCwHuopei> list, String date) {

        List<BtyCwHuopei> huopeiList = new ArrayList<>();//获取该店的货赔信息
        List<BtyCwHuopei> className = new ArrayList<>();//查询该店的品相类别
        List<BtyCwHuopei> timeList = new ArrayList<>();//获取所有时间段

        //获取该店的货赔信息
        huopeiList = baseMapper.getHuopeiList(list, date);
        //查询该店的品相类别
        className = baseMapper.selectClassNameList(list, date);
        //获取所有时间段
        timeList = baseMapper.selectTimeList(list, date);

        //要导出的list
        List<BtyCwHuopei> expList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(timeList)){
            for (BtyCwHuopei time : timeList) {

                if (CollectionUtil.isNotEmpty(className)) {
                    //循环该店品相类别
                    for (BtyCwHuopei name : className) {
                        //循环的时间相同(同一时间，同一家店)
                        if (name.getEndTime().equals(time.getEndTime()) && name.getShopCode().equals(time.getShopCode())){

                            BigDecimal sum1 = new BigDecimal(0);//理论耗用数量
                            BigDecimal sum2 = new BigDecimal(0);//实际耗用数量
                            BigDecimal sum3 = new BigDecimal(0);//耗用数量分差
                            BigDecimal sum4 = new BigDecimal(0);//耗用金额分差
                            BigDecimal sum5 = new BigDecimal(0);//耗用金额分差(酒水，只取负数)

                            if (CollectionUtil.isNotEmpty(huopeiList)) {

                                //循环该店货赔信息
                                for (BtyCwHuopei huopei : huopeiList) {
                                    //品相类别相同,店相同
                                    if (name.getClassName().equals(huopei.getClassName()) && time.getEndTime().equals(huopei.getEndTime())
                                            && huopei.getShopCode().equals(time.getShopCode())) {

                                        sum1 = sum1.add(huopei.getThNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getThNum()));
                                        sum2 = sum2.add(huopei.getRealNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getRealNum()));
                                        sum3 = sum3.add(huopei.getNumTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getNumTotal()));
                                        sum4 = sum4.add(huopei.getAmountTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
                                        //酒水耗用金额分差小计 只取负数的合计
                                        if(name.getClassName().contains("酒水") && ToolUtil.isNotEmpty(huopei.getAmountTotal())){
                                            sum5 = sum5.add(new BigDecimal(huopei.getAmountTotal()).compareTo(BigDecimal.ZERO) >= 0 ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
                                        }
                                        expList.add(huopei);
                                    }
                                }
                            }

                            name.setNum("小计");
                            name.setThNum(String.valueOf(sum1));//理论耗用数量
                            name.setRealNum(String.valueOf(sum2));//实际耗用数量
                            name.setNumTotal(String.valueOf(sum3));//耗用数量分差
                            if (name.getClassName().equals("酒水")){
                                name.setAmountTotal(String.valueOf(sum5));//耗用金额分差
                            }else {
                                name.setAmountTotal(String.valueOf(sum4));//耗用金额分差
                            }
                            expList.add(name);
                        }
                    }
                }

                String shopCode = time.getShopCode();

                if (shopCode != null){

                    //查询该店的盘亏信息
                    BtyCwPankui pankui = btyCwPankuiMapper.getPankui(shopCode, time.getEndTime());

                    BtyCwHuopei result = new BtyCwHuopei();
                    result.setShopCode(shopCode);
                    result.setShopName("类别名称");
                    result.setScmClassCode("盘亏金额");
                    result.setClassName("免赔金额");
                    result.setProCode("其他免赔金额");
                    result.setProName("备注");
                    result.setSpec("理论货赔金额");
                    result.setUnit("实际货赔金额");
                    result.setPrice("罚款金额");
                    result.setThNum("货赔合计");
                    expList.add(result);

                    BtyCwHuopei result1 = new BtyCwHuopei();
                    result1.setShopCode(shopCode);
                    result1.setShopName("清江鱼");
                    result1.setScmClassCode(pankui.getQjyPk());
                    result1.setClassName(pankui.getQjyMp());
                    result1.setProCode(pankui.getQjyOther());
                    result1.setProName(pankui.getQjyBz());
                    result1.setSpec(pankui.getQjyLlhp());
                    result1.setUnit(pankui.getQjySjhp());
                    result1.setPrice(pankui.getQjyFine());
                    result1.setThNum(pankui.getHeji());
                    result1.setBeginTime(time.getBeginTime());
                    result1.setEndTime(time.getEndTime());
                    expList.add(result1);

                    BtyCwHuopei result2 = new BtyCwHuopei();
                    result2.setShopCode(shopCode);
                    result2.setShopName("酱料");
                    result2.setScmClassCode(pankui.getJlPk());
                    result2.setClassName(pankui.getJlMp());
                    result2.setProCode(pankui.getJlOther());
                    result2.setProName(pankui.getJlBz());
                    result2.setSpec(pankui.getJlLlhp());
                    result2.setUnit(pankui.getJlSjhp());
                    result2.setPrice(pankui.getJlFine());
                    result2.setThNum(pankui.getHeji());
                    result2.setBeginTime(time.getBeginTime());
                    result2.setEndTime(time.getEndTime());
                    expList.add(result2);

                    BtyCwHuopei result3 = new BtyCwHuopei();
                    result3.setShopCode(shopCode);
                    result3.setShopName("酒水");
                    result3.setScmClassCode(pankui.getJsPk());
                    result3.setClassName(pankui.getJsMp());
                    result3.setProCode(pankui.getJsOther());
                    result3.setProName(pankui.getJsBz());
                    result3.setSpec(pankui.getJsLlhp());
                    result3.setUnit(pankui.getJsSjhp());
                    result3.setPrice(pankui.getJsFine());
                    result3.setThNum(pankui.getHeji());
                    result3.setBeginTime(time.getBeginTime());
                    result3.setEndTime(time.getEndTime());
                    expList.add(result3);

                    BtyCwHuopei huopei1 = new BtyCwHuopei();
                    expList.add(huopei1);
                }
            }
        }

        return expList;
    }

    /**
     * 没有营业额的店，计算
     * @param list
     * @param date
     * @return
     */
    private List<BtyCwHuopei> getHuopeiList(List<BtyCwHuopei> list, String date) {
        //要导出的list
        List<BtyCwHuopei> expList = new ArrayList<>();

        //获取该店的货赔信息
        List<BtyCwHuopei> huopeiList = baseMapper.getHuopeiList(list, date);
        //查询该店的品相类别
        List<BtyCwHuopei> className = baseMapper.selectClassNameList(list, date);
        //获取所有时间段
        List<BtyCwHuopei> timeList = baseMapper.selectTimeList(list, date);

        BigDecimal turnover = BigDecimal.ZERO;
        BigDecimal five = BigDecimal.ZERO;
        BigDecimal ten = BigDecimal.ZERO;
        String fiveM = "";//免赔（营业额百分之五取整）

        if (CollectionUtil.isNotEmpty(huopeiList)) {
            //获取营业额
            turnover = yybbMapper.getYye(huopeiList.get(0).getShopName(), huopeiList.get(0).getBeginTime(), huopeiList.get(0).getEndTime());
            if (turnover == null){
                turnover = BigDecimal.ZERO;
            }
            turnover.setScale(2, BigDecimal.ROUND_HALF_UP);//截取两位

            five = turnover.multiply(new BigDecimal(0.0005)).setScale(2, BigDecimal.ROUND_HALF_UP);//营业额万分之五
            ten = turnover.multiply(new BigDecimal(0.001)).setScale(2, BigDecimal.ROUND_HALF_UP);//营业额万分之十
        }

        //遍历时间
        if (CollectionUtil.isNotEmpty(timeList)){
            for (BtyCwHuopei time : timeList) {
                int i = 0;
                Map<String, String> map = new HashMap();

                if (CollectionUtil.isNotEmpty(className)) {
                    //循环该店品相类别
                    for (BtyCwHuopei name : className) {
                        //循环的时间相同
                        if (name.getEndTime().equals(time.getEndTime()) && name.getShopCode().equals(time.getShopCode())){

                            BigDecimal sum1 = new BigDecimal(0);//理论耗用数量
                            BigDecimal sum2 = new BigDecimal(0);//实际耗用数量
                            BigDecimal sum3 = new BigDecimal(0);//耗用数量分差
                            BigDecimal sum4 = new BigDecimal(0);//耗用金额分差
                            BigDecimal sum5 = new BigDecimal(0);//耗用金额分差(酒水，只取负数)

                            if (CollectionUtil.isNotEmpty(huopeiList)) {
                                //循环该店货赔信息
                                for (BtyCwHuopei huopei : huopeiList) {
                                    //品相类别相同
                                    if (name.getClassName().equals(huopei.getClassName()) && time.getEndTime().equals(huopei.getEndTime())) {


                                        sum1 = sum1.add(huopei.getThNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getThNum()));
                                        sum2 = sum2.add(huopei.getRealNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getRealNum()));
                                        sum3 = sum3.add(huopei.getNumTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getNumTotal()));
                                        sum4 = sum4.add(huopei.getAmountTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));

                                        //酒水耗用金额分差小计 只取负数的合计
                                        if(name.getClassName().contains("酒水") && ToolUtil.isNotEmpty(huopei.getAmountTotal())){
                                            sum5 = sum5.add(new BigDecimal(huopei.getAmountTotal()).compareTo(BigDecimal.ZERO) >= 0 ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
                                        }

                                        huopei.setTurnover(turnover);
                                        huopei.setFive(five);
                                        huopei.setTen(ten);

                                        expList.add(huopei);

                                    }
                                }
                            }

                            name.setNum("小计");
                            name.setThNum(String.valueOf(sum1));//理论耗用数量
                            name.setRealNum(String.valueOf(sum2));//实际耗用数量
                            name.setNumTotal(String.valueOf(sum3));//耗用数量分差
                            if (name.getClassName().equals("酒水")){
                                name.setAmountTotal(String.valueOf(sum5));//耗用金额分差
                            }else {
                                name.setAmountTotal(String.valueOf(sum4));//耗用金额分差
                            }
                            expList.add(name);

                            //修改数据库各小计
                            BtyCwHuopei huopei = new BtyCwHuopei();

                            fiveM = String.valueOf(Math.round(five.doubleValue()));//免赔（营业额百分之五取整）

                            if (name.getClassName().equals("冻货")) {
                                huopei.setDhThSum(String.valueOf(sum1));//冻货理论耗用数量小计
                                huopei.setDhRealSum(String.valueOf(sum2));//冻货实际耗用数量小计
                                huopei.setDhAmSum(String.valueOf(sum4));//冻货耗用金额分差小计
                                huopei.setDhNumSum(String.valueOf(sum3));//冻货耗用数量分差小计

                                //清江鱼盘亏
                                long qjyPk = Math.round(Double.valueOf(huopei.getDhAmSum()));
                                qjyPk = qjyPk >= 0 ? 0 : qjyPk;
                                //四舍五入取整
                                map.put("qjyPk", String.valueOf(qjyPk));

                                BigDecimal dhAmSum = new BigDecimal(huopei.getDhAmSum());
                                //理论货赔 -> 盘亏+免赔+其他免赔
                                BigDecimal qjyLlhp = new BigDecimal(map.get("qjyPk")).add(new BigDecimal(fiveM));
                                map.put("qjyLlhp", String.valueOf(qjyLlhp));
                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                                BigDecimal qjySjhp = qjyLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :qjyLlhp;
                                map.put("qjySjhp", String.valueOf(Math.round(Double.valueOf(qjySjhp.doubleValue()))));

                            } else if (name.getClassName().equals("酱料")) {
                                huopei.setJlThSum(String.valueOf(sum1));//酱料理论耗用数量小计
                                huopei.setJlRealSum(String.valueOf(sum2));//酱料实际耗用数量小计
                                huopei.setJlAmSum(String.valueOf(sum4));//酱料耗用金额分差小计
                                huopei.setJlNumSum(String.valueOf(sum3));//酱料耗用数量分差小计

                                //酱料盘亏
                                long jlPk = Math.round(Double.valueOf(huopei.getJlAmSum()));
                                jlPk = jlPk >= 0 ? 0 : jlPk;
                                //四舍五入取整
                                map.put("jlPk", String.valueOf(jlPk));

                                BigDecimal jlAmSum = new BigDecimal(huopei.getJlAmSum());

                                //理论货赔 -> 盘亏+免赔+其他免赔
                                BigDecimal jlLlhp = new BigDecimal(map.get("jlPk")).add(new BigDecimal(fiveM));
                                map.put("jlLlhp", String.valueOf(jlLlhp));
                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                                BigDecimal jlSjhp = jlLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jlLlhp;
                                map.put("jlSjhp", String.valueOf(Math.round(Double.valueOf(jlSjhp.doubleValue()))));

                            } else if (name.getClassName().equals("酒水")) {
                                huopei.setJsThSum(String.valueOf(sum1));//酒水理论耗用数量小计
                                huopei.setJsRealSum(String.valueOf(sum2));//酒水实际耗用数量小计
                                huopei.setJsAmSum(String.valueOf(sum5));//酒水耗用金额分差小计
                                huopei.setJsNumSum(String.valueOf(sum3));//酒水耗用数量分差小计

                                //酒水盘亏
                                long jsPk = Math.round(Double.valueOf(huopei.getJsAmSum()));
                                jsPk = jsPk >= 0 ? 0 : jsPk;
                                //四舍五入取整
                                map.put("jsPk", String.valueOf(jsPk));

                                BigDecimal jsAmSum = new BigDecimal(huopei.getJsAmSum());

                                //理论货赔 -> 盘亏+免赔+其他免赔(酒水没有免赔)
                                BigDecimal jsLlhp = new BigDecimal(map.get("jsPk"));
                                map.put("jsLlhp", String.valueOf(jsLlhp));
                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                                BigDecimal jsSjhp = jsLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO :jsLlhp;
                                map.put("jsSjhp", String.valueOf(Math.round(Double.valueOf(jsSjhp.doubleValue()))));

                            }else if (name.getClassName().equals("自采酒水")) {
                                huopei.setZcjsThSum(String.valueOf(sum1));//自采酒水理论耗用数量小计
                                huopei.setZcjsRealSum(String.valueOf(sum2));//自采酒水实际耗用数量小计
                                huopei.setZcjsAmSum(String.valueOf(sum5));//自采酒水耗用金额分差小计
                                huopei.setZcjsNumSum(String.valueOf(sum3));//自采酒水耗用数量分差小计

                                //自采酒水盘亏
                                long zcjsPk = Math.round(Double.valueOf(huopei.getZcjsAmSum()));
                                zcjsPk = zcjsPk >= 0 ? 0 : zcjsPk;
                                //四舍五入取整
                                map.put("zcjsPk", String.valueOf(zcjsPk));

                                BigDecimal zcjsAmSum = new BigDecimal(huopei.getZcjsAmSum());

                                //理论货赔 -> 盘亏+免赔+其他免赔(酒水没有免赔)
                                BigDecimal zcjsLlhp = new BigDecimal(map.get("zcjsPk"));
                                map.put("zcjsLlhp", String.valueOf(zcjsLlhp));
                                //实际货赔 -> 理论货赔金额大于0，取0; 小于0，取实际值
                                BigDecimal zcjsSjhp = zcjsLlhp.compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO : zcjsLlhp;
                                map.put("zcjsSjhp", String.valueOf(Math.round(Double.valueOf(zcjsSjhp.doubleValue()))));

                            }


                            huopei.setShopCode(time.getShopCode());

                            huopei.setBeginTime(name.getBeginTime());
                            huopei.setEndTime(name.getEndTime());

                            baseMapper.update(huopei);

                        }
                    }
                }

                String shopCode = time.getShopCode();

                if (shopCode != null){
                    //盘亏表新增相关数据
                    int count = btyCwPankuiMapper.count(shopCode, time.getEndTime());

                    //酒水盘亏 = 酒水 + 自采酒水 盘亏总计
                    int jspk = Integer.valueOf(ToolUtil.isNotEmpty(map.get("jsPk")) ? map.get("jsPk") : "0") +
                            Integer.valueOf(ToolUtil.isNotEmpty(map.get("zcjsPk")) ? map.get("zcjsPk") : "0");

                    //酒水理论货赔 盘亏+免赔+其他免赔(酒水没有免赔)
                    int jsLlhp = jspk;
                    //酒水实际货赔  -> 理论货赔金额大于0，取0; 小于0，取实际值
                    int jsSjhp = jsLlhp > 0 ? 0 : jsLlhp;

                    if (count == 0) {

                        BtyCwPankui btyCwPankui = new BtyCwPankui();
                        btyCwPankui.setShopCode(shopCode);
                        btyCwPankui.setQjyPk(ToolUtil.isNotEmpty(map.get("qjyPk")) ? map.get("qjyPk") : "0");//清江鱼盘亏
                        btyCwPankui.setJlPk(ToolUtil.isNotEmpty(map.get("jlPk")) ? map.get("jlPk") : "0");//酱料盘亏
                        btyCwPankui.setJsPk(String.valueOf(jspk));//酒水盘亏
                        btyCwPankui.setQjyMp(fiveM);//清江鱼免赔
                        btyCwPankui.setJlMp(fiveM);//酱料免赔
                        btyCwPankui.setJsMp("0");//酒水免赔
                        btyCwPankui.setQjyOther("0");//清江鱼其他免赔
                        btyCwPankui.setJlOther("0");//酱料其他免赔
                        btyCwPankui.setJsOther("0");//酒水其他免赔
                        btyCwPankui.setQjyLlhp(ToolUtil.isNotEmpty(map.get("qjyLlhp")) ? map.get("qjyLlhp") : "0");//清江鱼理论货赔
                        btyCwPankui.setJlLlhp(ToolUtil.isNotEmpty(map.get("jlLlhp")) ? map.get("jlLlhp") : "0");//酱料理论货赔
                        btyCwPankui.setJsLlhp(String.valueOf(jsLlhp));//酒水理论货赔
                        btyCwPankui.setQjySjhp(ToolUtil.isNotEmpty(map.get("qjySjhp")) ? map.get("qjySjhp") : "0");//清江鱼实际货赔
                        btyCwPankui.setJlSjhp(ToolUtil.isNotEmpty(map.get("jlSjhp")) ? map.get("jlSjhp") : "0");//酱料实际货赔
                        btyCwPankui.setJsSjhp(String.valueOf(jsSjhp));//酒水实际货赔
                        btyCwPankui.setQjyFine("0");//清江鱼罚款金额
                        btyCwPankui.setJlFine("0");//酱料罚款金额
                        btyCwPankui.setJsFine("0");//酒水罚款金额
                        btyCwPankui.setBeginTime(time.getBeginTime());//开始时间
                        btyCwPankui.setEndTime(time.getEndTime());//结束时间

                        //货赔合计=罚款金额+实际货赔
                        int heji = Integer.valueOf(ToolUtil.isNotEmpty(map.get("qjySjhp")) ? map.get("qjySjhp") : "0") +
                                Integer.valueOf(ToolUtil.isNotEmpty(map.get("jlSjhp")) ? map.get("jlSjhp") : "0") + jsSjhp;
                        btyCwPankui.setHeji(String.valueOf(heji));//货赔合计

                        btyCwPankuiMapper.insert(btyCwPankui);
                    }

                    //查询该店的盘亏信息
                    BtyCwPankui pankui = btyCwPankuiMapper.getPankui(shopCode, time.getEndTime());

                    //编辑数据库总计
                    BtyCwHuopei hp = new BtyCwHuopei();
                    hp.setShopCode(shopCode);//门店编号
                    hp.setBeginTime(time.getBeginTime());
                    hp.setEndTime(time.getEndTime());
                    hp.setTurnover(turnover);//营业额
                    hp.setFive(five);//营业额百分之五
                    hp.setTen(ten);//营业额百分之十
                    baseMapper.update(hp);

                    BtyCwHuopei result = new BtyCwHuopei();
                    result.setShopCode(shopCode);
                    result.setShopName("类别名称");
                    result.setScmClassCode("盘亏金额");
                    result.setClassName("免赔金额");
                    result.setProCode("其他免赔金额");
                    result.setProName("备注");
                    result.setSpec("理论货赔金额");
                    result.setUnit("实际货赔金额");
                    result.setPrice("罚款金额");
                    result.setThNum("货赔合计");
                    expList.add(result);

                    BtyCwHuopei result1 = new BtyCwHuopei();
                    result1.setShopCode(shopCode);
                    result1.setShopName("清江鱼");
                    result1.setScmClassCode(pankui.getQjyPk());//盘亏->冻货小计->耗用金额分差小计
                    result1.setClassName(fiveM);//免赔->营业额5%
                    //理论货赔金额
                    result1.setProCode(pankui.getQjyOther() == null ? "0" : pankui.getQjyOther());//其他免赔金额
                    result1.setProName(pankui.getQjyBz());//备注
                    result1.setSpec(pankui.getQjyLlhp());//理论货赔金额->盘亏+免赔+其他免赔
                    result1.setUnit(pankui.getQjySjhp());//实际货赔金额->理论货赔金额大于0，取0;小于0，取实际值
                    result1.setPrice(pankui.getQjyFine() == null ? "0" : pankui.getQjyFine());//罚款金额
                    result1.setThNum(pankui.getHeji());//货赔合计

                    result1.setBeginTime(time.getBeginTime());
                    result1.setEndTime(time.getEndTime());
                    expList.add(result1);

                    BtyCwHuopei result2 = new BtyCwHuopei();
                    result2.setShopCode(shopCode);
                    result2.setShopName("酱料");
                    result2.setScmClassCode(pankui.getJlPk());//盘亏->酱料小计->耗用金额分差小计
                    result2.setClassName(fiveM);//免赔->营业额5%
                    //理论货赔金额
                    result2.setProCode(pankui.getJlOther() == null ? "0" : pankui.getJlOther());//其他免赔金额
                    result2.setProName(pankui.getJlBz());//备注
                    result2.setSpec(pankui.getJlLlhp());//理论货赔金额->盘亏+免赔+其他免赔
                    result2.setUnit(pankui.getJlSjhp());//实际货赔金额->理论货赔金额大于0，取0;小于0，取实际值
                    result2.setPrice(pankui.getJlFine() == null ? "0" : pankui.getJlFine());//罚款金额
                    result2.setThNum(pankui.getHeji());//货赔合计

                    result2.setBeginTime(time.getBeginTime());
                    result2.setEndTime(time.getEndTime());
                    expList.add(result2);

                    BtyCwHuopei result3 = new BtyCwHuopei();
                    result3.setShopCode(shopCode);
                    result3.setShopName("酒水");
                    result3.setScmClassCode(pankui.getJsPk());//盘亏->酒水小计->耗用金额分差小计
                    result3.setClassName(pankui.getJsMp());//免赔->酒水没有免赔
                    //理论货赔金额
                    result3.setProCode(pankui.getJsOther() == null ? "0" : pankui.getJsOther());//其他免赔金额
                    result3.setProName(pankui.getJsBz());//备注
                    result3.setSpec(pankui.getJsLlhp());//理论货赔金额->盘亏+免赔+其他免赔
                    result3.setUnit(pankui.getJsSjhp());//实际货赔金额->理论货赔金额大于0，取0;小于0，取实际值
                    result3.setPrice(pankui.getJsFine() == null ? "0" : pankui.getJsFine());//罚款金额
                    result3.setThNum(pankui.getHeji());//货赔合计

                    result3.setBeginTime(time.getBeginTime());
                    result3.setEndTime(time.getEndTime());
                    expList.add(result3);


                    BtyCwHuopei huopei1 = new BtyCwHuopei();
                    expList.add(huopei1);
                }
            }
        }
        return expList;
    }

    /**
     * 批量导出excel样式 - pc
     * @param list
     * @param timeList
     * @return
     */
    private InputStream expBatch(List<BtyCwHuopei> list, List<BtyCwHuopei> timeList) {
        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式

        //TODO-2 每一列字段名
        String[] titles = new String[]{"", "门店编号", "门店名称", "品相类别编号", "品相类别名称", "品相编号", "品相名称", "规格", "单位",
                "非税成本单价", "销售数量", "实际耗用数量", "耗用数量分差", "耗用金额分差"};

        // 字段名所在表格的宽度，数量应与列字段名数量一致
        int[] ints = new int[]{1000, 3000, 5000, 5000, 5000, 3000, 5000, 5000, 3000, 3000, 3000, 3000, 3000, 3000};

        //TODO-3 设置总标题内容，没有可略过
        SXSSFRow row1 = sheet.createRow(0);
        SXSSFCell cell0 = row1.createCell(0);

        //合并单元格
        CellRangeAddress regionFist = new CellRangeAddress(0, 0, 0, 13); //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
        sheet.addMergedRegion(regionFist);
        //设置每一列的字段名

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String begin = sdf.format(timeList.get(0).getBeginTime());
        String end = sdf.format(timeList.get(timeList.size() - 1).getEndTime());
        BigDecimal turnover = BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP);
        if (ToolUtil.isNotEmpty(list)){
            turnover = list.get(0).getTurnover();
        }

        cell0.setCellValue("档口原料用量差异分析-货赔 (业务日期:" + begin + " 至 " + end + "营业额：" + turnover + ")");
        cell0.setCellStyle(header);

        CellStyle cellStyle1 = wb.createCellStyle();
        cellStyle1.setBorderBottom(BorderStyle.THIN);
        cellStyle1.setBorderLeft(BorderStyle.THIN);
        cellStyle1.setBorderRight(BorderStyle.THIN);
        cellStyle1.setBorderTop(BorderStyle.THIN);
        cellStyle1.setWrapText(true);// 设置自动换行
        cellStyle1.setAlignment(HorizontalAlignment.CENTER);// 设置单元格字体显示居中（左右方向）
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);// 设置单元格字体显示居中(上下方向)
        //设置单元格背景颜色
        cellStyle1.setFillPattern(FillPatternType.BIG_SPOTS);
        cellStyle1.setFillForegroundColor(IndexedColors.ROSE.getIndex());
        cellStyle1.setFillBackgroundColor(IndexedColors.ROSE.getIndex());


        //TODO-4 设置内容标题
        //内容的标题所在行
        int concentitleStartRow = 2;
        //设置表头样式
        ExcelFormatUtil.initContentTitleEX(sheet, content, concentitleStartRow, titles, ints);

        //TODO-5 从第contentStartRow行开始为内容数据
        int contentStartRow = 3;

        if (list != null && list.size() > 0) {

            int p = 0;
            for (int i = 0; i < list.size() - 1; i++) {

                BtyCwHuopei huopei = list.get(i);

                SXSSFRow row = sheet.createRow(contentStartRow + i - 1);
                int j = 0;
                int k = list.size() - 5;
                SXSSFCell cell = row.createCell(j++);

                if (ToolUtil.isNotEmpty(huopei.getShopName())){
                    //序号
                    cell.setCellValue(huopei.getNum());
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }

                    // 门店编号
                    cell = row.createCell(j++);
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellValue(huopei.getShopCode());
                        cell.setCellStyle(content);
                    }

                    // 门店名称
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getShopName());
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }

                    //品相类别编号
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getScmClassCode());
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }

                    // 品项类别名称
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getClassName());
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }

                    // 品项编号
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getProCode());
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }

                    // 品项名称
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getProName());
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }

                    // 规格
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getSpec());
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }

                    // 单位
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getUnit());
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }

                    //非税单价
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getPrice());
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }

                    //销售数量
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getThNum() == null ? "0" : huopei.getThNum().toString());
                    if (ToolUtil.isEmpty(huopei.getShopName())){
                        cell.setCellValue("");
                    }
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }

                    //实际耗用数量
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getRealNum());
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }

                    //耗用数量分差
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getNumTotal());
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }

                    //耗用金额分差
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getAmountTotal());
                    if (k <= i || (ToolUtil.isNotEmpty(huopei.getShopName()) && (
                            huopei.getShopName().equals("类别名称") || huopei.getShopName().equals("清江鱼") ||
                                    huopei.getShopName().equals("酱料") || huopei.getShopName().equals("酒水")))){
                        cell.setCellStyle(cellStyle1);
                    }else {
                        cell.setCellStyle(content);
                    }
                }

                if (i == list.size() - 2){
                    //合并单元格(货赔合计)
                    CellRangeAddress regioni = new CellRangeAddress(contentStartRow + i - 3, contentStartRow + i - 1, 10, 10); //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
                    sheet.addMergedRegion(regioni);
                }

                if (i < list.size() - 4 && ToolUtil.isEmpty(huopei.getShopCode())){
                    //合并单元格(货赔合计)
                    CellRangeAddress regioni = new CellRangeAddress(contentStartRow + i - 4, contentStartRow + i - 2, 10, 10); //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
                    sheet.addMergedRegion(regioni);

                    //合并单元格表头
                    CellRangeAddress regionHead = new CellRangeAddress(contentStartRow + i - 1, contentStartRow + i - 1, 0, 13); //设置标题：指定 4 个参数，起始行，结束行，起始列，结束列,
                    sheet.addMergedRegion(regionHead);

                    if (ToolUtil.isNotEmpty(list.get(i+1).getBeginTime())){
                        String beginTime = sdf.format(list.get(i+1).getBeginTime());
                        String endTime = sdf.format(list.get(i+1).getEndTime());
                        turnover = list.get(i+1).getTurnover();

                        cell.setCellValue("档口原料用量差异分析-货赔 (业务日期:" + beginTime + " 至 " + endTime + "营业额：" + turnover + ")");
                        cell.setCellStyle(header);
                    }

                }
            }
        }

        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null) {
                        inputStream1.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return inputStream1;
    }


}
